I have lots of existing C++ code with template classes that have implementations in the .cpp files. I want to add a template function to one such class. My problem is that I cannot make the compiler instantiate the function template.
I've created a stripped example demonstrating the problem. I want to add the member function convert()
, with an own template parameter LenNew
:
template <typename Number, int Len>
class MyClass {
public:
// the function I'm trying to add
template <int LenNew>
MyClass<Number, LenNew> convert();
// other methods I want to keep this way
void function(); // implemented in .cpp file
private:
Number n[Len];
};
In the existing setup, the .cpp file implements methods and instantiates the class template:
template <typename Number, int Len>
void MyClass<Number, Len>::function()
{
// implementation
}
// instantiate template-class with specific template parameters
template class MyClass<double, 1>;
So I added the implementation for my new member function, and tried to instantiate the template, which doesn't seem to work:
template <typename Number, int Len>
template <int LenNew>
MyClass<Number, LenNew> MyClass<Number, Len>::convert()
{
// implement...
}
// try instantiate
template<> template<> MyClass<double, 2> MyClass<double, 1>::convert<2>();
It compiles fine, but I get an undefined reference when I try to use convert()
from a different .cpp file:
main.cpp:(.text+0x1c): undefined reference to `MyClass<double, 2> MyClass<double, 1>::convert<2>()'
Here is a Gist with the demo program: https://gist.github.com/md2k7/8503385
Sorry, there seem to be a lot of very similar questions, but I could still not grasp what is wrong.