定义同一类型的模板类的静态constexpr成员
对于模板类,
template <typename T>
struct Test {
T data;
static const Test constant;
};
定义 static constexpr
专用类型的成员变量是可以的:
template <>
inline constexpr Test<int> Test<int>::constant {42};
https://godbolt.org/z/o4c4yojmf
虽然在定义 statation constancpr
直接从模板类中直接从模板类中定义 static constancpr
时,编译器会差异。
template <typename T>
inline constexpr Test<T> Test<T>::constant {42};
https://godbolt.org/z/m8jdx3wzm
编译。
clang
忽略 constexpr
定义中的指定符。
msvc
... /std:C ++ 17
效果很好,但是/std:C ++ 20
由于重新定义而拒绝。
我了解到 constexpr
可以应用对于定义,变量或变量模板
在此示例中,哪一个是对的?为什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为gcc在 static 数据成员名为
常数
是普通数据成员变量(尽管它仍然被视为模板的实体)。并且由于
常数
是普通数据成员变量“> dcl.constexpr#1.Sessence-1 适用于此:(强调地雷)
因此,作为您在类模板之后提供的构造,只是普通静态数据成员 constance>常数,给定的示例是良好的。
请
注意,不提及模板实体,而是仅提及“变量”和“变量模板”,并且由于
constant
是一个变量(普通),因此应适用于constand> constant
。I think GCC is correct in accepting the given example. This is because the
static
data member namedconstant
is an ordinary data member variable(although it is still considered a templated entity).And since
constant
is an ordinary data member variable, dcl.constexpr#1.sentence-1 is applicable to it:(emphasis mine)
Thus, as the construct that you have provided after the class template is nothing but an out-of-class definition for the ordinary static data member
constant
, the given example is well-formed.Note
Note that dcl.constexpr#1.sentence-1 doesn't mention templated entity, but instead only mention "variable" and "variable template" and since
constant
is a variable(ordinary), the same should be applicable toconstant
.