c++ - if constexpr() gives an error in C++17 -


i have read constexpr in c++17 using reference link.

then, made c++ program test constexpr :

#include <iostream>  int = 10;  int func()  {     if constexpr (i == 0)         return 0;     else if (i > 0)         return i;     else         return -1; }  int main()  {     int ret = func();     std::cout<<"ret : "<<ret<<std::endl; } 

but, compiler give error:

main.cpp: in function 'int func()': main.cpp:8:25: error: value of 'i' not usable in constant expression      if constexpr (i == 0)                          ^ main.cpp:4:5: note: 'int i' not const  int = 10; 

why gives error?

you misunderstood meaning of if constexpr. not test const expression performed @ runtime, test of logical expression performed @ compile time.

the construct similar #if of preprocessor, in other branch eliminated, along code may otherwise not compile.

this work:

template<int  i> int func()  {     if constexpr (i == 0)         return 0;     else if constexpr (i > 0)         return i;     else         return -1; } 

the compiler knows value of i @ compile time, depending on value 1 of 3 branches going remain in compiled code.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -