c++ - 如果 constexpr 给出错误,则实例化模板函数为 false

标签 c++ c++17 clang++ if-constexpr

考虑以下程序:

#include <iostream>

template<typename... Params_t>
constexpr int constexprValue(Params_t...) { return 5; }

int main()
{
    const bool flag = true;

    if constexpr(flag)
    {
        constexpr int value = constexprValue(1, 2, 3);
        std::cout << value << "\n";
    }
}

这可以编译并正常工作。但是,如果将 flag 更改为 false,则 clang(Apple LLVM 版本 10.0.0 (clang-1000.10.44.4))会给出编译器错误:

error: constexpr variable 'value' must be initialized by a constant expression
undefined function 'constexprValue<int, int, int>' cannot be used in a constant expression

这是 clang 中的错误吗?

最佳答案

是的,这是一个错误,已通过此 commmit to clang: [Sema] Discarded statment should be an evaluatable context. 修复其中有以下描述:

The constexpr evaluator was erroring out because these templates weren't defined. Despite being used in a discarded statement, we still need to constexpr evaluate them, which means that we need to instantiate them. Fixes PR37585.

Differential revision: https://reviews.llvm.org/D48322

并包括以下测试:

namespace PR37585 {
template <class T> struct S { static constexpr bool value = true; };
template <class T> constexpr bool f() { return true; }
template <class T> constexpr bool v = true;

void test() {
  if constexpr (true) {}
  else if constexpr (f<int>()) {}
  else if constexpr (S<int>::value) {}
  else if constexpr (v<int>) {}
}
}

如果我们尝试现场测试 with godbolt with an older clang version我们获得了与您的示例所看到的非常相似的错误诊断:

error: constexpr if condition is not a constant expression
else if constexpr (f<int>()) {}
                   ^~~~~~~~

note: undefined function 'f<int>' cannot be used in a constant expression

该修复源自bug report: constexpr if condition is not a constant expression and std::is_same .

关于c++ - 如果 constexpr 给出错误,则实例化模板函数为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53187528/

相关文章:

c++ - 如何混淆本地变量?

java - Java 中的私有(private)扩展

c++ - 一个函数的类模板特化

c++ - 如果p以根路径开头,为什么std::filesystem::path::append替换当前路径

c++ - 投入 constexpr 函数 : do we need wrapping condition?

c++ - 有没有办法在 g++/clang++ 中使用自定义修改?

c++ - 当我用 clang 编译我的代码时,gcov 抛出内存不足错误

c++ - 类中的unique_ptr如何使用它们

c++ - 警告 : comparison between pointer and integer

由于虚拟析构函数/clang 的 C++ 链接器警告