c++ - 在 constexpr-if 条件下比较 constexpr 函数参数导致错误

标签 c++ constexpr c++17 static-assert if-constexpr

我正在尝试比较 constexpr-if 语句中的函数参数。

这是一个简单的例子:

constexpr bool test_int(const int i) {
  if constexpr(i == 5) { return true; }
 else { return false; }
}

但是,当我使用带有以下标志的 GCC 7 编译它时: g++-7 -std=c++1z test.cpp -o test 我收到以下错误消息:

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; }

但是,如果我用不同的函数替换 test_int:

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

然后下面的代码编译没有错误:

int main() {
  constexpr int i = 5;
  static_assert(test_int_no_if(i));
  return 0;
}

我不明白为什么 constexpr-if 版本无法编译,特别是因为 static_assert 工作得很好。

如有任何建议,我们将不胜感激。

谢谢!

最佳答案

来自 constexpr if :

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

然后,从constant expression :

Defines an expression that can be evaluated at compile time.

显然,i == 5不是常量表达式,因为 i是在运行时评估的函数参数。这就是编译器提示的原因。

当你使用函数时:

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

然后它可能会在编译时被评估,这取决于它的参数在编译时是否已知。

如果i定义如下:

constexpr int i = 5;

然后是i的值在编译期间已知并且test_int_no_if也可能在编译期间进行评估,从而可以在 static_assert 中调用它.

另请注意,将函数参数标记为 const不会使其成为编译时间常量。这只是意味着您不能更改函数内部的参数。

关于c++ - 在 constexpr-if 条件下比较 constexpr 函数参数导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45377244/

相关文章:

C++11 constexpr 函数传递参数

c++ - 如何使用 Clang 指定 C++17 中 utf-16 字符串文字的字节序?

c++ - 采用字符数组的 constexpr 函数的正确定义是什么?

c++ - constexpr 和函数体 = 删除 : what's the purpose?

c++ - 为什么 main() 中的调用 `A a(c);` 没有歧义?

c++ - C++线程安全 vector 插入

c++ - 在构造函数/赋值运算符之外使用右值引用

C++ ,这个 goto 语句是否有保证?

PHP 扩展 : undefined symbol: curl_easy_setopt in Unknown on line 0

c++ - 在某些函数中使用增量运算符