如何定义类模板的静态数据成员?
我想这样做:
template <typename T>
struct S
{
...
static double something_relevant = 1.5;
};
但我不能,因为 something_relevant
不是整数类型。它不依赖于 T
,但现有代码依赖于它是 S
的静态成员。
由于 S 是模板,我无法将定义放入编译文件中。我该如何解决这个问题?
I'd like to do this:
template <typename T>
struct S
{
...
static double something_relevant = 1.5;
};
but I can't since something_relevant
is not of integral type. It doesn't depend on T
, but existing code depends on it being a static member of S
.
Since S is template, I cannot put the definition inside a compiled file. How do I solve this problem ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需在标头中定义它:
由于它是模板的一部分,与所有模板一样,编译器将确保它仅定义一次。
Just define it in the header:
Since it is part of a template, as with all templates the compiler will make sure it's only defined once.
从 C++17 开始,您现在可以将静态成员声明为
inline
,这将在类定义中定义变量:live: https://godbolt.org/g/bgSw1u
Since C++17, you can now declare the static member to be
inline
, which will define the variable in the class definition:live: https://godbolt.org/g/bgSw1u
这会起作用
This will work