考虑以下程序:
#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/