C++ 类模板中的静态成员初始化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3229883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Static member initialization in a class template
提问by Alexandre C.
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
.
但我不能,因为something_relevant
不是整数类型。它不依赖于T
,但现有代码依赖于它是S
.
Since S is template, I cannot put the definition inside a compiled file. How do I solve this problem ?
由于 S 是模板,我不能将定义放在编译文件中。我该如何解决这个问题?
回答by sbi
Just define it in the header:
只需在标题中定义它:
template <typename T>
struct S
{
static double something_relevant;
};
template <typename T>
double S<T>::something_relevant = 1.5;
Since it is part of a template, as with all templates the compiler will make sure it's only defined once.
由于它是模板的一部分,与所有模板一样,编译器将确保它只定义一次。
回答by xaxxon
Since C++17, you can now declare the static member to be inline
, which will define the variable in the class definition:
从 C++17 开始,您现在可以将静态成员声明为inline
,这将在类定义中定义变量:
template <typename T>
struct S
{
...
static inline double something_relevant = 1.5;
};
回答by Prasoon Saurav
This will work
这将工作
template <typename T>
struct S
{
static double something_relevant;
};
template<typename T>
double S<T>::something_relevant=1.5;