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

时间:2018-11-07 10:22:58

标签: 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

这是c中的错误吗?

2 个答案:

答案 0 :(得分:1)

是的,这似乎是Apple版本的clang中的一个错误,我能够使用clang版本5和更高版本以及gcc版本7.1和更高版本编译代码。

Matt Godbold有一个很棒的网站,可以用各种不同的编译器来编译代码片段。

Here是您在Godbolt中的示例的链接。

答案 1 :(得分:1)

是的,这是此commmit to clang: [Sema] Discarded statment should be an evaluatable context. 修复的错误,该错误具有以下描述:

  

constexpr评估程序出错了,因为这些模板不是   定义。尽管在废弃的语句中使用过,我们仍然需要constexpr   评估它们,这意味着我们需要实例化它们。修复了PR37585。

     

差异修订: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