c++ - Comparing constexpr function parameter in constexpr-if condition causes error -
i'm trying compare function parameter inside constexpr-if statement.
here simple example:
constexpr bool test_int(const int i) { if constexpr(i == 5) { return true; } else { return false; } } however, when compile gcc 7 following flags: g++-7 -std=c++1z test.cpp -o test following error message:
test.cpp: in function 'constexpr bool test_int(int)': test.cpp:3:21: error: 'i' not constant expression if constexpr(i == 5) { return true; } however, if replace test_int different function:
constexpr bool test_int_no_if(const int i) { return (i == 5); } then following code compiles no errors:
int main() { constexpr int = 5; static_assert(test_int_no_if(i)); return 0; } i don't understand why constexpr-if version fails compile, since static_assert works fine.
any advice on appreciated.
thanks!
from constexpr if:
in constexpr if statement, value of condition must contextually converted constant expression of type bool.
then, constant expression:
defines expression can evaluated @ compile time.
obviously, i == 5 not constant expression, because i function parameter evaluated @ run time. why compiler complains.
when use function:
constexpr bool test_int_no_if(const int i) { return (i == 5); } then might evaluated during compile time depending on whether it's parameter known @ compile time or not.
if i defined like:
constexpr int = 5; then value of i known during compile time , test_int_no_if might evaluated during compile making possible call inside static_assert.
also note, marking function parameter const not make compile time constant. means cannot change parameter inside function.
Comments
Post a Comment