Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 with different values
}

It's common case in D lang, but I didn't found info about C++17.

Of course, it is possible to use something like

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

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

like image 206
aaalex88 Avatar asked Aug 15 '17 12:08

aaalex88


1 Answers

There is no way this code could work. The problem is that x is out of scope when you are calling bar. But there is a workaround:

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

bar(t);

To explain a little bit, it uses instantly invoked lambda expression along with auto return type deduction. Therefore we are giving t value in place and it does not get out of the scope.

Of course, it wouldn't work if the if statement couldn't have been evaluated at compile time. And if you want to do some runtime operations inside of this lambda you cannot have t as constexpr, but it will still work.

like image 151
Daniel Jodłoś Avatar answered Sep 29 '22 20:09

Daniel Jodłoś