问题描述
我遇到了以下情况:
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:错误:redeclaration'Foo :: s'不同在'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:声明'constexpr const char Foo :: s [12]'类外不是定义[-fpermissive]
const char Foo :: s [];
GCC 6.0:
'constexpr'需要用于静态数据成员的类初始化'const char Foo :: s [12]'非整数类型[-fpermissive]
我发现似乎讨论混合 constexpr
和 const
,但它集中在初始化器是否是常量表达式,而不是定义和声明是否可以不同to const const。
是否允许为 constexpr T
静态数据成员定义 const T
?
constexpr
-specifier本身不是类型的一部分,但添加 const
([dcl.constexpr] / 9)这在您的第二个声明中。虽然一个函数(或函数模板)的不同声明必须在 constexpr
-ness中与[dcl.constexpr] / 1一致,但是对于变量声明不存在这样的规则。 / p>
查看错误,基本上使用您的示例。
I came across the following situation:
struct Foo
{
static constexpr char s[] = "Hello world";
};
const char Foo::s[];
This code snippet compiles with Clang 3.7 (with -std=c++11
and -std=c++14
), but GCC (4.8, 6.0, same language settings) gives the error I would have expected:
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]
I found this old question that seems to discuss mixing constexpr
and const
, but it focusses on whether initializers are constant expressions, rather on whether definition and declaration can differ with regard to constness.
Is it allowed to provide the definition for a constexpr T
static data member as a const T
?
Your code is well-formed. The constexpr
-specifier is not itself part of the type but adds const
([dcl.constexpr]/9), which is present in your second declaration. Although different declarations of one function (or function template) have to agree in constexpr
-ness as per [dcl.constexpr]/1, no such rule exists for variable declarations.
See bug #58541, which basically uses your example.
这篇关于混合constexpr声明和const定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!