草庐IT

c++ - 此错误消息是否正确 : non-type template argument is not a constant expression

coder 2023-06-02 原文

以下程序可以使用 GCC 5.2 编译,但不能使用 clang 3.6:

constexpr bool flag();

template <bool b = flag()>
constexpr bool test() 
{ 
    return b;
}

int main() 
{
}

我用 clang 得到的错误信息是:

main.cpp:3:20: error: non-type template argument is not a constant expression
template <bool b = flag()>
                   ^~~~~~
main.cpp:3:20: note: undefined function 'flag' cannot be used in a constant expression
main.cpp:1:16: note: declared here
constexpr bool flag();
               ^
main.cpp:4:16: error: no return statement in constexpr function
constexpr bool test() 
               ^

我的问题是:谁是对的?或者,换句话说:程序是否格式错误?

最佳答案

我会说 clang 是对的:

来自标准:

[temp.param] 14.1 #9

9 A default template-argument is a template-argument (14.3) specified after = in a template-parameter. [...]

和 [temp.arg.nontype] 14.3.2

1 A template-argument for a non-type template-parameter shall be a converted constant expression (5.20) of the type of the template-parameter.

和 [expr.const] 5.20

2 A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:

[...]

(2.3) — an invocation of an undefined constexpr function or an undefined constexpr constructor;

由于flag()已声明但未定义,因此它不是常量表达式,违反了14.3.2。

关于c++ - 此错误消息是否正确 : non-type template argument is not a constant expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34561884/

有关c++ - 此错误消息是否正确 : non-type template argument is not a constant expression的更多相关文章

随机推荐