in foo.h:
#ifndef FOO_H
#define FOO_H
enum Rat
{
A,
B
};
class Foo
{
public:
template<Rat r>
int aMemberFunc(int, int, int);
};
#endif
in foo.cpp:
#include "foo.h"
namespace {
template<Rat r>
int helper(int a, int b)
{
return a+b*((int) r);
}
}
template<Rat r>
int Foo::aMemberFunc(int a, int b, int c)
{
return a + helper<r>(b,c);
}
in main.cpp:
#include "foo.h"
#include <iostream>
using namespace std;
int main(void)
{
Foo test;
cout << test.aMemberFunc<B>(1,2,3) << endl;
}
I compile with g++ main.cpp foo.cpp and I get:
main.cpp:(.text+0x88): undefined reference to `int Foo::aMemberFunc<(Rat)1>(int, int, int)'
collect2: ld returned 1 exit status
I would prefer not to move stuff to the header because that brings along the helper and a lot of baggage, I tried to add a file fooimpl.cpp:
#include "foo.h"
#include "foo.cpp"
template int Foo::aMemberFunc<A>(int,int,int);
template int Foo::aMemberFunc<B>(int,int,int);
and then compile with g++ fooimpl.cpp main.cpp foo.cpp
This was per the suggestion of Dietmar (thanks!) but as soon as I add a function void rand(); in the header of foo.h and void rand() {} in foo.cpp the above trick yields this error:
foo.cpp:(.text+0x0): multiple definition of `Foo::rand()’
/tmp/ccoCtGMk.o:fooimpl.cpp:(.text+0x0): first defined here
how do i work around this?
You need to instantiate your function, not specialize it: