[英]Partial template specialization for initialization of static data members of template classes
对于特定参数,如何初始化模板类的静态数据成员?
我知道模板与其他类不同,并且仅实例化了项目中使用的模板。 我可以为不同的参数列出许多不同的初始化方法,并让编译器使用合适的方法吗?
例如,下面的方法是否有效,如果不能,那么正确的方法是什么? :
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文件而不是标头中。
int someClass<int>::someData = 5;
double someClass<double>::someData = 5.0;
这也是使用静态数据成员初始化的部分模板专门化工作:
// .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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.