首页 > 解决方案 > 在 C++ 中的类模板中是否可以有一个通用的、非专用的静态成员?

问题描述

假设我有一个类模板,我想根据我加载的 json 配置文件中的变量来实例化它。在那个 json 文件中,一个变量会说:"TYPEA""TYPEB".

此外,我有一个存储所有可能类型的枚举,因此我可以切换大小写来实例化一种或另一种专业化。现在我需要一个 std::map 来将此枚举与配置文件中的对应值相关联,例如:{"TYPEA" = TYPEA, "TYPEB" = TYPEB}.

在我加载了字符串之后,我想检查它是否是一个有效值,所以我查找了地图,如果键不存在,我会抛出一个异常。如果密钥存在,我通过枚举切换大小写并实例化适当的模板特化。

所有这一切意味着我有一个static std::map所有专业通用的。这是可能的,还是这样做的愚蠢方式?它应该在头文件还是 tpp 文件中定义?地图定义有问题。

#include <iostream>
#include <map>

template <typename T>
class A
{
    public:

        T m_t;
        enum classType{TYPEA, TYPEB, TYPEC};
        static std::map<std::string, classType> m_typeMap;
        classType m_type;

        A(T& t) : m_t(t) {}
};


template <typename T>
std::map<std::string, A<T>::classType> A<T>::m_typeMap =   // here I get the error
{{"TYPEA", A::classType::TYPEA},
 {"TYPEB", A::classType::TYPEB},
 {"TYPEC", A::classType::TYPEC}};


int main()
{
    std::cout << A::m_typeMap["TYPEA"] << std::endl;
}

编译器错误是:

../main.cpp:19:38: error: type/value mismatch at argument 2 in template parameter list for 'template<class _Key, class _Tp, class _Compare, class _Alloc> class std::map'
 std::map<std::string, A<T>::classType> A<T>::m_typeMap =
                                      ^
../main.cpp:19:38: note:   expected a type, got 'A<T>::classType'
../main.cpp:19:38: error: template argument 4 is invalid
../main.cpp:19:46: error: conflicting declaration 'int A<T>::m_typeMap'
 std::map<std::string, A<T>::classType> A<T>::m_typeMap =
                                              ^~~~~~~~~
../main.cpp:11:49: note: previous declaration as 'std::map<std::__cxx11::basic_string<char>, A<T>::classType> A<T>::m_typeMap'
         static std::map<std::string, classType> m_typeMap;
                                                 ^~~~~~~~~
../main.cpp:19:46: error: declaration of 'std::map<std::__cxx11::basic_string<char>, A<T>::classType> A<T>::m_typeMap' outside of class is not definition [-fpermissive]
 std::map<std::string, A<T>::classType> A<T>::m_typeMap =
                                              ^~~~~~~~~
../main.cpp: In function 'int main()':
../main.cpp:27:18: error: 'template<class T> class A' used without template parameters
     std::cout << A::m_typeMap["TYPEA"] << std::endl;

标签: c++c++11templatesstaticmember

解决方案


在 C++ 中的模板类中是否可以有一个通用的、非专用的静态成员?

制作那个“类模板”,更容易理解它的实际含义。

如果您使类模板从一个公共基础继承,那当然是可能的。

struct base { // non-template base
    // static functions and variables 
};

template<typename T>
class Foo : public base {}

推荐阅读