模板类中的静态变量导致 C2371 'redefinition; different basic types'

Static variable in template class causing C2371 'redefinition; different basic types'

本文关键字:redefinition different types basic C2371 静态 变量      更新时间:2023-10-16

我有一个带有静态成员变量的模板类。然而,在编译时,我得到了以下错误:

C2371: 'S_TYPES' : redefinition; different basic types

这是有问题的课程:

// This all is in Type.h
template<class T>
class Type
{
private:
    static std::map<unsigned int, Type<T>> S_TYPES;
};
template<class T>
std::map<unsigned int, Type<T>> Type<T>::S_TYPES;

如何修复此处的错误?

OP一看到错误就编辑了这个问题:您定义的类型与声明的类型不同:

template<class T>
class Type
{
private:
    static std::map<unsigned int, Type<T>> S_TYPES;
};
template<class T>
std::map<unsigned int, Type<T>, TypeInfoComparator> Type<T>::S_TYPES; // different

你应该确保它们匹配:

template<class T>
class Type
{
private:
    static std::map<unsigned int, Type<T>> S_TYPES;
};
template<class T>
std::map<unsigned int, Type<T>> Type<T>::S_TYPES;