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
}

This is a common case in D lang, but I did not find any information about C ++ 17.

Of course, you can use something like

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

but only in elementary cases. Even different initializers (as indicated above) pose a big problem.

+6
source share
2 answers

This code cannot work. The problem is that it xgoes beyond the scope of the call bar. But there is a workaround:

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

bar(t);

, . t .

, , if . , t constexpr, .

+6

, .

-, , . , : int x = 5 .

-, if constexpr if constexpr. , , , , then/else. (, else-block x ?)

bar() if body foo() x, ....

+2

All Articles