Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

c++ - Comparing constexpr function parameter in constexpr-if condition causes error

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From constexpr if:

In a constexpr if statement, the value of condition must be a contextually converted constant expression of type bool.

Then, from constant expression:

Defines an expression that can be evaluated at compile time.

Obviously, i == 5 is not a constant expression, because i is a function parameter which is evaluated at run time. That is why the compiler complains.

When you use a function:

constexpr bool test_int_no_if(const int i) { return (i == 5); }

then it might be evaluated during the compile time depending on whether it's parameter is known at compile time or not.

If i is defined like:

constexpr int i = 5;

then the value of i is known during the compile time and test_int_no_if might be evaluated during the compile too making it possible to call it inside static_assert.

Also note, that marking function parameter as const does not make it a compile time constant. It just means that you cannot change the parameter inside the function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...