简体   繁体   English

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

[英]Static member initialization in a class template

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. 但是我不能,因为something_relevant不是整数类型。 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. 由于S是模板,因此无法将定义放入编译文件中。 How do I solve this problem ? 我该如何解决这个问题?

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. 由于它是模板的一部分,因此与所有模板一样,编译器将确保仅定义一次。

This will work 这会起作用

template <typename T>
 struct S
 {

     static double something_relevant;
 };

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

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;
};

live: https://godbolt.org/g/bgSw1u 直播: https//godbolt.org/g/bgSw1u

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM