【问题标题】:error C2908: explicit specialization; '' has already been instantiated错误 C2908:显式特化; '' 已经被实例化了
【发布时间】:2019-11-01 22:35:12
【问题描述】:

我有一个简单的模板单例类,如果要保持简单易读,我简化了(删除了安全、断言等。这不是问题的主题)

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 上搜索并搜索,找不到类似的问题和解决方案。

干杯, 赛博

【问题讨论】:

  • 模板及其特化应在头文件中定义(.h 而不是 .cpp)。你能显示这个最小示例的每个 .h 和 .cpp 文件的内容吗?由于全局模板函数 Create 的放置错误,似乎正在发生隐式实例化。

标签: c++ templates instantiation specialization


【解决方案1】:

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

我忘了检查 dllimport/dllexport 签名。在我的 Singleton 类和 Create func 前面添加它们解决了这个错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    相关资源
    最近更新 更多