views:

83

answers:

2

After having some problems with these two linker errors on SO, I have them again. However, this time the source seems to lie at another point.

compiler error shows that it cannot find a function with signature ""public: unsigned int __thiscall MyClass::myFunction<unsigned int>(int)const ".

However, moving the contents of myClass.cpp to main.cpp works. Don't know why (all other content of myClass.cpp doesn't have this problem. (other functions are not templated).

myClass.h

#ifndef X
#define X
class MyClass {
public:
    template<class T>
    T myFunction (int someArgument) const;
};
#endif

myClass.cpp

#include "myClass.h"
template<class T>
T MyClass::myFunction (int someArgument) const {
    return T();
}

main.cpp

#include "myClass.h"
int main () {
    MyClass a();
    a.myFunction<unsigned int>(42);
    return 0;
}

What can I do to fix this problem?

+1  A: 

Function templates have to be defined in header files. Templates of class methods are not an exception to that rule. Move the definition of the method from 'MyClass.cpp' to the header file 'MyClass.h'.

myClass.h

#ifndef X
#define X

class MyClass {
public:
    template<class T>
    T myFunction (int someArgument) const;
};

template<class T>
T MyClass::myFunction (int someArgument) const {
    return T();
}

#endif

Your 'MyClass.cpp' is not needed at all until the first non-template member of 'MyClass'.

AndreyT
+1  A: 

Because in main.cpp, the compiler can find the definition of the template function.

Templates cannot be compiled, the compiler needs to be able to see the definition of the file, and it's can't see across files.

Either include myClass.cpp in myClass.h, or just define everything in the header.

GMan