模板类静态数据成员初始化的部分模板特化 [英] Partial template specialization for initialization of static data members of template classes

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

问题描述

对于特定参数,如何以不同的方式初始化模板类的静态数据成员?

How would one initialize static data members of a template class differently for particular parameters?

我知道模板与其他类型的类不同,只有在项目中使用的才会被实例化.我可以为不同的参数列出许多不同的初始化,并让编译器使用合适的方法吗?

I understand that templates are different than other kinds of classes and only what is used in the project ever gets instantiated. Can I list a number of different initializations for different parameters and have the compiler use whichever is appropriate?

例如,以下是否有效,如果无效,正确的方法是什么?:

For example, does the following work, and if not what is the correct way to do this? :

template<class T>
class someClass
{
   static T someData;
   // other data, functions, etc...
};

template<class T>
T someClass::someData = T.getValue();

template<>
int someClass<int>::someData = 5;

template<>
double someClass<double>::someData = 5.0;

// etc...

推荐答案

应该可以.您可能需要将这些放入 .c 文件而不是标题中.

Should work. You may need to put these into the .c file instead of the header.

int someClass<int>::someData = 5;
double someClass<double>::someData = 5.0;

这里还有一个工作部分模板特化,初始化静态数据成员:

Here is also a working partial template specialization with initialization of static data members:

// .h
template <class T, bool O>
struct Foo {
    T *d_ptr;
    static short id;
    Foo(T *ptr) : d_ptr(ptr) { }
};
template <class T>
struct Foo<T, true> {
    T *d_ptr;
    static short id;
    Foo(T *ptr) : d_ptr(ptr) { }
};
template<class T, bool O>
short Foo<T, O>::id = 0;
template<class T>
short Foo<T, true>::id = 1;

//.cpp
int main(int argc, char *argv[])
{
    Foo<int, true> ft(0);
    Foo<int, false> ff(0);
    cout << ft.id << " " << ff.id << endl;
}

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

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