对模板成员函数的未定义引用

C++ undefined reference to template member function

本文关键字:未定义 引用 函数 成员      更新时间:2023-10-16
//Forward declaration
class MyType;
class Factory{
    template<class T>
    static T* CreateObject(T& newOb){
         return &newOb;
    }
    //Other non template functions 
}
//In main (error causing line)
MyType tmptype;
MyType* newMyType = Factory::CreateObject<MyType>(tmptype);

这段代码导致这个错误:对' MyType* Factory::CreateObject(MyType&)'的未定义引用

我也得到这个警告:警告:没有在命令行上指定——enable-auto-import,自动导入已被激活

另外,如果我使用int类型,它仍然不能工作,这就排除了该类型没有被正确包含的可能性。

函数接受一个引用,所以你需要传递给它一个变量,编译器可能会接受这个变量的地址。

class Factory{
public:
    template<class T>
    static T* CreateObject(T& newOb){
        return &newOb;
    }
    //Other non template functions
};
class MyType {};
int main() {
    MyType a;
    MyType* newMyType = Factory::CreateObject<MyType>(a);
}

您没有定义MyType。如果要向Factory类传递要创建的对象,则需要定义要传递的类型。没有传入对象的类型,工厂类是不可能创建对象的!所以你的MyType应该是一个原生的类型定义,或者是一个定义你自己的数据类型的结构/类。

在理想的情况下,

class MyType{
     //Some data structure or type that you want to use.
};

class Factory{
public:
    template<class T>
    static T* CreateObject(T& newOb){
        return &newOb;
    }
    //Other non template functions
}

将允许您的工厂类创建您自己类型的对象。

答案很简单。你的函数调用语法错误。你只需要调用Factory::CreateObject(tmptype);

你不需要像模板化类那样实例化一个模板化函数。