Skip to content

Instantly share code, notes, and snippets.

@cidermole
Last active January 3, 2016 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cidermole/8503385 to your computer and use it in GitHub Desktop.
Save cidermole/8503385 to your computer and use it in GitHub Desktop.
Problem in C++ function template instantiation from class template
#include "myclass.hh"
int main() {
MyClass<double, 1> myclass;
MyClass<double, 2> newclass;
myclass.function();
newclass = myclass.template convert<2>();
newclass.function();
return 0;
}
MAIN = program
OBJECTS = main.o myclass.o
all : $(MAIN)
$(MAIN) : $(OBJECTS)
g++ -o $@ $(OBJECTS)
%.o : %.cpp
g++ -c $<
clean:
rm -rf $(OBJECTS) $(MAIN)
#include "myclass.hh"
#include <iostream>
using namespace std;
template <typename Number, int Len>
void MyClass<Number, Len>::function()
{
cout << "function() in MyClass with Len=" << Len << endl;
}
template <typename Number, int Len>
template <int LenNew>
MyClass<Number, LenNew> MyClass<Number, Len>::convert()
{
MyClass<Number, LenNew> newclass;
// make new from old here... not relevant for demo
return newclass;
}
// instantiate template-class with specific template parameters
template class MyClass<double, 1>;
template class MyClass<double, 2>;
// instantiate template-function from template-class with specific template parameters
// against this error: main.cpp:(.text+0x23): undefined reference to `MyClass<double, 2> MyClass<double, 1>::convert<2>()'
template<> template<> MyClass<double, 2> MyClass<double, 1>::convert<2>();
// but doesn't help! still same error
template <typename Number, int Len>
class MyClass {
public:
void function();
template <int LenNew>
MyClass<Number, LenNew> convert();
private:
Number n[Len];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment