类模板中的静态成员初始化 [英] Static member initialization in a class template

查看:249
本文介绍了类模板中的静态成员初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做:

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

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

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.

由于S是模板,我不能把定义放在一个编译文件中。如何解决这个问题?

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

推荐答案

只要在标题中定义:

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.

这篇关于类模板中的静态成员初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆