I'm trying to move an explicit specialization of a template member function to a .cpp file, but the linker keeps saying "unresolved external symbol".
Foo.hpp
struct Color {};
class Foo
{
public:
template<typename T> int add(T b);
template<> int add(Color b);
};
template<typename T>
int Foo::add(T b)
{
return 0;
}
Foo.cpp
#include "Foo.hpp"
template<>
int Foo::add(Color b)
{
return 0;
}
template int Foo::add(Color b);
Bar.cpp
#include "Foo.hpp"
void f() {
Foo dbg;
dbg.add(5);
dbg.add(Color());
}
I tried to explicitly instantiate the member function in Foo.cpp. Why doesn't this have any effect?
I'm aware of two solutions: I could move the definition of int Foo::add(Color)
into the .hpp, and mark it inline. Or I could force the instantiation in Foo.cpp like this:
void dummy() {
Foo().add(Color());
}
How come I can't use template int Foo::add(Color b)
to instantiate the function? Am I using the wrong syntax?