C++ 混合constexpr声明和const定义
我遇到了以下情况:C++ 混合constexpr声明和const定义,c++,c++11,static-members,C++,C++11,Static Members,我遇到了以下情况: struct Foo { static constexpr char s[] = "Hello world"; }; const char Foo::s[]; 此代码段使用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’ con
struct Foo
{
static constexpr char s[] = "Hello world";
};
const char Foo::s[];
此代码段使用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]
我发现这似乎讨论了混合constexpr
和const
,但它关注的是初始值设定项是否是常量表达式,而不是定义和声明是否可以在常量方面有所不同
是否允许将
constepr T
静态数据成员定义为const T
?您的代码格式正确。constexpr
-说明符本身不是该类型的一部分,而是添加了const
([dcl.constexpr]/9),它出现在您的第二个声明中。尽管根据[dcl.constexpr]/1,一个函数(或函数模板)的不同声明必须在constexpr
-ness中一致,但变量声明不存在此类规则
请参阅基本上使用您的示例的bug。另请参阅@ShafikYaghmour:谢谢,很有趣。GCC错误消息似乎变得更加混乱。在4.8中,它是一致的,尽管它与标准相矛盾,但新的错误信息相当模糊。