类模板中的静态成员初始化

时间:2022-08-21 22:52:36

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.

但我不能,因为相关的东西不是整型的。它不依赖于T,但是现有的代码依赖于它是S的静态成员。

Since S is template, I cannot put the definition inside a compiled file. How do I solve this problem ?

由于S是模板,所以我不能将定义放在已编译的文件中。我该如何解决这个问题?

2 个解决方案

#1


142  

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.

由于它是模板的一部分,与所有模板一样,编译器将确保它只定义一次。

#2


28  

This will work

这将工作

template <typename T>
 struct S
 {

     static double something_relevant;
 };

 template<typename T>
 double S<T>::something_relevant=1.5;

#1


142  

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.

由于它是模板的一部分,与所有模板一样,编译器将确保它只定义一次。

#2


28  

This will work

这将工作

template <typename T>
 struct S
 {

     static double something_relevant;
 };

 template<typename T>
 double S<T>::something_relevant=1.5;