Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ specialization of template function inside template class

What is the C++ syntax for specializing a template function that's inside a template class? For example, consider that I have the following two classes and their usage. I would like to be able to provide specialized implementations of the method X::getAThing() for different types. E.g.: int, std::string, arbitrary pointer or class, etc.

template <class c1> class X { public:    template<typename returnT> returnT getAThing(std::string param);    static std::string getName(); private:    c1 theData; };  // This works ok... template <class c1> std::string X<c1>::getName() {    return c1::getName(); }  // This blows up with the error: // error: prototype for 'int X<c1>::getAThing(std::string)' does not match any in class 'X<c1>' template <class c1> template <typename returnT> int X<c1>::getAThing(std::string param) {    return getIntThing(param); // Some function that crunches on param and returns an int. }  // More specialized definitions of getAThing() for other types/classes go here...  class Y { public:    static std::string getName() { return "Y"; } };  int main(int argc, char* argv[]) {    X<Y> tester;    int anIntThing = tester.getAThing<int>(std::string("param"));    cout << "Name: " <<  tester.getName() << endl;    cout << "An int thing: " << anIntThing << endl; } 

I've been trying to guess at the correct syntax for the specialization for at least an hour, and can't figure anything out that will compile. Any help would be greatly appreciated!

like image 419
Ogre Psalm33 Avatar asked Feb 14 '11 16:02

Ogre Psalm33


1 Answers

AFAIK (and the standards experts can correct me), you cannot specialize a templated function of a class template without specializing the class itself...

i.e. the following I think will work:

template <> template <> int X<Y>::getAThing<int>(std::string param) {    return getIntThing(param); // Some function that crunches on param and returns an int. } 
like image 55
Nim Avatar answered Oct 26 '22 18:10

Nim