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

Initialize a templated class's static member that uses a template argument as the type?

本文关键字:静态成员 类型 参数 初始化      更新时间:2023-10-16

我有:

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]

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

啊,正确的语法是:

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

由于所有的模板参数,我感到很困惑

与这个问题的答案相似,但并不完全重叠