Partial template specialization for initialization of static data members of template classes

前提是你 提交于 2019-12-08 12:28:44

问题


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...

回答1:


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


来源:https://stackoverflow.com/questions/7670374/partial-template-specialization-for-initialization-of-static-data-members-of-tem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!