I'm trying to compare a function parameter inside a constexpr-if statement.
Here is a simple example:
constexpr bool test_int(const int i) {
if constexpr(i == 5) { return true; }
else { return false; }
}
However, when I compile this with GCC 7 with the following flags:
g++-7 -std=c++1z test.cpp -o test
I get the following error message:
test.cpp: In function 'constexpr bool test_int(int)':
test.cpp:3:21: error: 'i' is not a constant expression
if constexpr(i == 5) { return true; }
However, if I replace test_int
with a different function:
constexpr bool test_int_no_if(const int i) { return (i == 5); }
Then the following code compiles with no errors:
int main() {
constexpr int i = 5;
static_assert(test_int_no_if(i));
return 0;
}
I don't understand why the constexpr-if version fails to compile, especially since the static_assert works just fine.
Any advice on this would be appreciated.
Thanks!
See Question&Answers more detail:os