初始化一个使用模板参数作为类型的模板类静态成员?

时间:2013-07-25 20:32:35

标签: c++ templates static initialization

我有:

template<typename TypeA, typename TypeB>
class MyClass
{
     public:
     static TypeA StaticA;
     static TypeB StaticB;

     //...other stuff....
}; 

如何初始化'StaticA'(和StaticB)?

如果我这样做:(在头文件中,在类的声明下但不在其中)

template<>
typename MyClass<TypeA, TypeB>::TypeA MyClass<TypeA, TypeB>::StaticA = TypeA();

给我:

'TypeA' was not declared in this scope.
'TypeB' was not declared in this scope.
template argument 1 is invalid
template argument 2 is invalid

而且:

template<typename TypeA, typename TypeB>
typename MyClass<TypeA, TypeB>::TypeA MyClass<TypeA, TypeB>::StaticA = TypeA();

给我:

conflicting declaration 'typename MyClass<TypeA, TypeB>::TypeA MyClass<TypeA, TypeB>::StaticA'
'MyClass<TypeA, TypeB>::StaticA' has a previous declaration as 'TypeA MyClass<TypeA, TypeB>::StaticA'
declaration of 'TypeA MyClass<TypeA, TypeB>::StaticA' outside of class is not definition [-fpermissive]

初始化使用模板参数作为类型的模板化类的静态成员的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

啊,正确的语法是:

template<typename TypeA, typename TypeB>
TypeA ResourceFactory<TypeA, TypeB>::StaticA = TypeA();

我原来的问题是:

template<typename TypeA, typename TypeB>
typename MyClass<TypeA, TypeB>:: TypeA MyClass<TypeA, TypeB>::StaticA = TypeA();
^remove^ ^-------remove--------^

由于所有模板参数,我感到困惑。 =)

answer相似但并非完全重叠。