简体   繁体   中英

C++ undefined reference to template member function

//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);

This code causes this error: undefined reference to `MyType* Factory::CreateObject(MyType&)'

I also get this warning: warning: auto-importing has been activated without --enable-auto-import specified on the command line

Additionally, it still doesn't work if I use an int type, which rules out the possibility of the type not being included properly.

The function takes a reference, so you need to pass it a variable of which the compiler may take an address.

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);
}

You have not defined MyType. If you are passing the Factory class the object that you want to create then you need to define the type that you are passsing. Without passing in the type of object that the factory class is not possible to create one! So You MyType should be either a typedef for primitive or struct/class that defines your own data type.

Ideally,

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

and

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

Would allow your factory class to create an object of your own type.

The answer is simple. Your function calling syntax is wrong. All you need to do is call Factory::CreateObject(tmptype);

You need not instantiate a templated function the way you do for templated classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM