错误 C2908:显式专用化; 已被实例化

error C2908: explicit specialization; '' has already been instantiated

本文关键字:实例化 专用 C2908 错误      更新时间:2023-10-16

>我有一个简单的模板单例类,我简化了如果保持简单易读(删除了保护措施,断言等,这不是问题的主题(

template< class  T> T* Create();
template <class T>
class CSingleton
{
    public:
    static  T*      CreateInstance() { return m_instance = Create<T>(); }
    static  void    DestroyInstance() { delete m_instance;}
    protected:
    static T* m_instance;
};

如您所见,我使用全局函数 T* Create(( 来新建指针,因为我的类可能是一个抽象类。 所以如果我像这样定义 CreateInstance:

static  T*      CreateInstance() { return m_instance = new T; }

它将生成一个错误,我无法实例化抽象类。

所以这里有一个非常简单的例子,产生错误,班级 :

class MyClass : public CSingleton<MyClass>
{
};

以及我的 CPP 中全局函数的定义

template< > MyClass* Create< MyClass >()
{
    return nullptr;// just for the compilation demonstration
}

如果我不定义这个,链接器将输出它找不到 Create(( 的错误,如果我定义函数,我得到这个错误:

error C2908:  explicit specialization; 'T *Create<T>(void)' has already been instantiated
error C2908:         with
error C2908:         [
error C2908:             T=MyClass
error C2908:         ]
我在

这个问题上被困了 2 个小时,我找不到解决方案,我在 StackOverflow 上搜索了谷歌和搜索,找不到类似的问题和解决方案。

干杯塞布

所有这些类都在 DLL 库中,但我仅在构建库时遇到编译器/链接错误。

我忘了检查dllimport/dllexport签名。在我的单例类前面添加它们并创建函数解决了此错误。