类型不完整的C ++静态constexpr字段 [英] C++ static constexpr field with incomplete type
问题描述
我正在尝试编译此代码,但是g ++抱怨 0
的类型不完整。这是否意味着在C ++中,结构体不能包含自身的静态constexpr
实例?如果是,为什么?
I'm trying to compile this code, but g++ complains about ZERO
having an incomplete type. Does this mean that in C++ a struct cannot contain a static constexpr
instance of itself? If so, why?
struct Cursor
{
size_t row,column;
static constexpr Cursor ZERO {0,0};
//error: constexpr const Cursor Cursor::ZERO has incomplete type
};
编辑:我知道 Cursor
不能具有当我声明 0
时为完整类型。我想知道的是:有什么办法可以使 0
属于 Cursor
并仍然是 constexpr
?
I understand that Cursor
cannot have a complete type when I declare ZERO
. What I'd like to know is: is there any way I can have ZERO
belonging to Cursor
and still being constexpr
?
推荐答案
不幸的是,您根本无法做到这一点!
Unfortunately, you simply cannot do this!
某些静态constexpr
成员可以内联初始化:
Some static constexpr
members may be initialised inline:
[C ++ 11 9.4.2 / 3]:
[..] A静态可以使用
数据成员;如果是这样,则其声明应指定一个constexpr
说明符在类定义中声明文字类型的
brace-or-equal-initializer ,其中每个 assignment-expression 的 initializer-clause 常数表达式。 [..]
[C++11 9.4.2/3]:
[..] Astatic
data member of literal type can be declared in the class definition with theconstexpr
specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [..]
Cursor
是一个
以及 Cursor
本身作为静态变量的使用
自己的类型中的数据成员不是问题,只要您在词法命名空间范围内对其进行初始化:
And the use of Cursor
itself as a static
data member within its own type is not a problem, as long as you initialise it at lexical namespace scope:
[C ++ 11:9.4.2 / 2]:
静态
数据成员的声明在其类中的定义不是定义,并且可能是不完整的类型,而不是具有cv限定的void。静态
数据成员的定义应出现在包含该成员的类定义的名称空间范围中。在名称空间范围的定义中,静态
数据成员应使用::
运算符通过其类名进行限定。静态
数据成员的定义中的初始化器表达式在其类的范围内(3.3.7) 。
[C++11: 9.4.2/2]:
The declaration of astatic
data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void. The definition for astatic
data member shall appear in a namespace scope enclosing the member’s class definition. In the definition at namespace scope, the name of thestatic
data member shall be qualified by its class name using the::
operator. The initializer expression in the definition of astatic
data member is in the scope of its class (3.3.7).
但是您不能使用 constexpr
做到这一点:
But you can't do that with constexpr
:
[C ++ 11:7.1.5 / 9]:
A <$ c $对象声明中使用的c> constexpr 说明符将对象声明为const
。这样的对象应具有文字类型并应进行初始化。 [..]
[C++11: 7.1.5/9]:
Aconstexpr
specifier used in an object declaration declares the object asconst
. Such an object shall have literal type and shall be initialized. [..]
我认为所有这些措辞都可以得到改善,但与此同时,我认为您将必须使零
成为封闭名称空间中的非成员。
I think all of this wording could be improved but, in the meantime, I think you're going to have to make ZERO
a non-member in the enclosing namespace.
这篇关于类型不完整的C ++静态constexpr字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!