0

I made an if-constexpr statement and it seems to generate both workflow paths...?

running this code :

#include <iostream> class Chaste { template<typename T> friend struct TheChosenOne; private: int x = 0; Chaste() = default; Chaste(int x): x(x) {} }; int main() { std::allocator<Chaste> alloc{}; Chaste* new_node = std::allocator_traits<std::allocator<Chaste>>::allocate(alloc, 1); if constexpr (std::is_constructible_v<Chaste, int>){ new(new_node) Chaste(5); }else{ static_assert(false); } return 0; } 

somehow I get both the static_assert and private constructor call CE`s:

 /home/bibaboba/CLionProjects/untitled4/main.cpp: In function ‘int main()’: /home/bibaboba/CLionProjects/untitled4/main.cpp:18:31: error: ‘Chaste::Chaste(int)’ is private within this context 18 | new(new_node) Chaste(5); | ^ /home/bibaboba/CLionProjects/untitled4/main.cpp:9:5: note: declared private here 9 | Chaste(int x): x(x) {} | ^~~~~~ /home/bibaboba/CLionProjects/untitled4/main.cpp:20:23: error: static assertion failed 20 | static_assert(false); | ^~~~~ 

According to cppreference, only one flow should be compiled (the one with static_assert) since the is_constructible expression is false, so why is a private constructor call CE generated?

3
  • I know both flows may be generated if the condition in an if-statement isn't constexpr, but isn't is_constructible constexpr? Commented Aug 4, 2024 at 10:35
  • tl;dr - if constexpr can discard branches only in a template, and only when the condition is dependent on template parameters. Furthermore, static_assert(false) in that situation is only well-formed since C++23 Commented Aug 4, 2024 at 10:44
  • 1
    You should not even have to use that constexpr if in main, make your Chaste class itself only compilable it it is constructible from int and make your Chaste class itself specialize on allocator type... so all in all the design looks a bit weird (maybe it is the result of you trying to make an MRE) Commented Aug 4, 2024 at 10:59

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.