Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to specialize templated member functions of non-templated classes?

suppose I have a file alpha.h:

class Alpha {
public:
    template<typename T> void foo();
};

template<> void Alpha::foo<int>() {}
template<> void Alpha::foo<float>() {}

If I include alpha.h in more than one cpp file and compile with GCC 4.4, it complains there are multiple definitions of foo<int> and foo<float> across multiple object files. Makes sense to me, so I change the last two lines to:

template<> extern void Alpha::foo<int>() {}
template<> extern void Alpha::foo<float>() {}

But then GCC says:

explicit template specialization cannot have a storage class

ok... so how am I supposed to do this correctly? I'm worried that C++ doesn't allow what I'm trying to do in the first place, in which case is there a good idiom that will accomplish the same thing?

like image 978
Kyle Avatar asked Jul 16 '10 16:07

Kyle


1 Answers

use inline keyword

template<> inline void Alpha::foo<int>() {}

alternatively, provide implementation in separate cpp file

like image 135
Anycorn Avatar answered Sep 30 '22 14:09

Anycorn