【问题标题】:Mixing constexpr declarations and const definitions混合 constexpr 声明和 const 定义
【发布时间】:2015-10-10 12:07:45
【问题描述】:

我遇到了以下情况:

struct Foo
{
    static constexpr char s[] = "Hello world";
};

const char Foo::s[];

此代码 sn-p 使用 Clang 3.7(使用 -std=c++11-std=c++14)编译,但 GCC(4.8、6.0,相同的语言设置)给出了我预期的错误:

GCC 4.8:

in.cpp:6:19: error: redeclaration ‘Foo::s’ differs in ‘constexpr’
 const char Foo::s[];
                   ^
in.cpp:3:27: error: from previous declaration ‘Foo::s’
     static constexpr char s[] = "Hello world";
                           ^
in.cpp:6:19: error: declaration of ‘constexpr const char Foo::s [12]’ outside of class is not definition [-fpermissive]
 const char Foo::s[];

GCC 6.0:

‘constexpr’ needed for in-class initialization of static data member ‘const char Foo::s [12]’ of non-integral type [-fpermissive]

我发现this old question 似乎在讨论混合constexprconst,但它关注的是初始化程序是否是常量表达式,而不是定义和声明在常量方面是否可以不同。

是否允许将constexpr T 静态数据成员定义为const T

【问题讨论】:

标签: c++ c++11 static-members


【解决方案1】:

您的代码格式正确。 constexpr-specifier 本身不是类型的一部分,而是添加了 const ([dcl.constexpr]/9),它出现在您的第二个声明中。尽管根据 [dcl.constexpr]/1,一个函数(或函数模板)的不同声明必须在 constexpr-ness 中达成一致,但变量声明不存在这样的规则。

请参阅错误#58541,它基本上使用了您的示例。

【讨论】:

    猜你喜欢
    • 2021-03-28
    • 1970-01-01
    • 2023-04-08
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    • 2013-04-09
    • 1970-01-01
    相关资源
    最近更新 更多