c++ - Can `if constexpr` be used to declare variables with different types and init-expr -


for example:

void foo() {     if constexpr (...)         int x = 5;     else         double x = 10.0;     bar(x); // calls different overloads of bar different values } 

it's common case in d lang, didn't found info c++17.

of course, possible use like

std::conditional<..., int, double>::type x; 

but in elementary cases. different initializators (as above) creates big problem.

there no way code work. problem x out of scope when calling bar. there workaround:

constexpr auto t = []() -> auto {   if constexpr(/* condition */) return 1;   else return 2.9; }();  bar(t); 

to explain little bit, uses instantly invoked lambda expression along auto return type deduction. therefore giving t value in place , not out of scope.

of course, wouldn't work if if statement couldn't have been evaluated @ compile time. , if want runtime operations inside of lambda cannot have t constexpr, still work.


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -