![](/img/trans.png)
[英]Is it possible to have a static constexpr member with type X of template class X?
[英]Define a static constexpr member of same type of a template class
对于模板 class,
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
当编译器在没有实例化的情况下直接从模板 class 定义static constexpr
成员时,结果会有所不同:
template <typename T>
inline constexpr Test<T> Test<T>::constant {42};
https://godbolt.org/z/M8jdx3WzM
GCC
编译。
clang
忽略定义中的constexpr
说明符。
MSVC
... /std:c++17
运行良好,但/std:c++20
由于重新定义而拒绝。
在这个例子中,哪个是正确的? 为什么?
我认为 GCC 在接受给定示例时是正确的。 这是因为名为constant
的数据成员static
是一个普通的数据成员变量(尽管它仍然被认为是一个模板化实体)。
而由于constant
是一个普通的数据成员变量, dcl.constexpr#1.sentence-1适用于它:
constexpr 说明符应仅应用于变量或变量模板的定义或 function 或 function 模板的声明。
(强调我的)
因此,由于您在 class 模板之后提供的构造只不过是普通 static 数据成员constant
的类外定义,因此给定的示例格式正确。
template <typename T>
constexpr Test<T> Test<T>::constant {42}; //this is an out-of-class definition for the ordinary static data member variable `constant`
请注意, dcl.constexpr#1.sentence-1没有提及模板化实体,而是仅提及“变量”和“变量模板”,并且由于constant
是一个变量(普通),因此同样适用于constant
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.