c++ - 具有未触及的非 constexpr 参数 : Who is correct, clang 或 gcc 的 constexpr?

标签 c++ c++11 c++14 constexpr

我有 4 个测试用例,我相信它们都是有效的:

constexpr int f(int const& /*unused*/){
    return 1;
}

void g(int const& p){
    constexpr int a = f(p); // clang error, gcc valid

    int v = 0;
    constexpr int b = f(v); // clang valid, gcc valid

    int const& r = v;
    constexpr int c = f(r); // clang error, gcc error

    int n = p;
    constexpr int d = f(n); // clang valid, gcc valid
}

int main(){
    int p = 0;
    g(p);
}

Clang 和 GCC 仅在第一个测试用例上有所不同。

我使用 clang 4 & 5 (20170319) 和 GCC 7.0.1 (20170221) 进行了测试。

如果我是对的,它将大大简化 boost::hana 在 static_assert 中的使用。

最佳答案

[expr.const]/2 :

An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would evaluate one of the following expressions:

  • [...]
  • an id-expression that refers to a variable or data member of reference type unless the reference has a preceding initialization and either

    • it is initialized with a constant expression or

    • its lifetime began within the evaluation of e;

  • [...]

pr 都不满足条件。因此 f(p)f(r) 都不是核心常量表达式,因此它们都不能用于初始化 constexpr 变量。 Clang 是正确的。

关于c++ - 具有未触及的非 constexpr 参数 : Who is correct, clang 或 gcc 的 constexpr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42997847/

相关文章:

c++ - 将 OpenCV 与 std::Array 结合使用

c++ - 具有更多模板参数的部分特化

c++ - 在同一命令中使用变量时移至 lambda

c++ - 使用 BigInteger 数组时出现 Malloc 错误

c++ - 一个好的 vector 散列函数

c++ boost asio超时以阻止连接

c++ - 包含自己的 map

c++ - 非模板类中的模板化 friend 类,其中 friend 也使用该类

c++ - 帮助在 UNIX 上学习 C++。操作系统、机器、书籍、IDE ..全部一堆!

c++ - 使用 static_cast 实现的转换运算符