如何定义类模板的静态数据成员?

发布于 2024-09-09 12:04:50 字数 285 浏览 1 评论 0原文

我想这样做:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

暖心男生 2024-09-16 12:04:50

只需在标头中定义它:

template <typename T>
struct S
{
    static double something_relevant;
};

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

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

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.

杀手六號 2024-09-16 12:04:50

从 C++17 开始,您现在可以将静态成员声明为 inline,这将在类定义中定义变量:

template <typename T>
struct S
{
    ...
    static inline double something_relevant = 1.5;
};

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:

template <typename T>
struct S
{
    ...
    static inline double something_relevant = 1.5;
};

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

三岁铭 2024-09-16 12:04:50

这会起作用

template <typename T>
 struct S
 {

     static double something_relevant;
 };

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

This will work

template <typename T>
 struct S
 {

     static double something_relevant;
 };

 template<typename T>
 double S<T>::something_relevant=1.5;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文