5

My problem is as follows. This is my method:

template<class T>
T my_function();

These specializations work ok:

template<>
int my_function();   //my_function<int>();

template<>
float my_function();  //my_function<flot>();
...

But these don't:

1.

    template<>
    template<class T>   
    std::list<T> my_function();   //my_function<std::list<class T> >();

2.

    template<class T>   
    template<>
    std::vector<T> my_function();   //my_function<std::vector<class T> >();

I get the error:

too many template-parameter-lists

so my question is: How do I specialize a template with a template class?

Tom Zych
  • 13,329
  • 9
  • 36
  • 53
eddy
  • 488
  • 5
  • 18

2 Answers2

5

You cannot partially specialize a function template, but you can for class. So you may forward the implementation to a class as the following:

namespace detail {

    template <typename T> struct my_function_caller { T operator() () { /* Default implementation */ } };
    template <> struct my_function_caller<int> { int operator() () { /* int implementation */ } };
    template <> struct my_function_caller<float> { float operator() () { /* float implementation */ } };
    template <typename T> struct my_function_caller<std::list<T>> { std::list<T> operator() () { /* std::list<T> implementation */ } };
    template <typename T> struct my_function_caller<std::vector<T>> { std::vector<T> operator() () { /* std::vector<T> implementation */ } };

}


template<class T>
T my_function() { return detail::my_function_caller<T>()(); }
Jarod42
  • 203,559
  • 14
  • 181
  • 302
4

You can't partially specialize a function, if you declare

template<class T>
T my_function() {
    ....
}

template<class T>
std::list<T> my_function() {
    ....
}

and try to call the first with

my_function<int>();

since partial specializations are not allowed for functions these declarations will be conflicting (those are actually two different declarations, and what's worse: they both match for that instantiation).

What you can do is wrap your function into a class or a struct that can handle partial specializations for it:

#include <iostream>
#include <list>
using namespace std;

template<class T> struct funWrapper {
  T my_function() {
    cout << "normal" << endl;
    return 0;
  }
};

template<class T> struct funWrapper<std::list<T>> {
  std::list<T> my_function() {
    cout << "stdlist";
    return std::list<T>();
  }
};



int main() {
  funWrapper<int> obj;
  obj.my_function();

  funWrapper<std::list<int>> obj2;
  obj2.my_function();
  return 0;
}

http://ideone.com/oIC2Hf

Marco A.
  • 43,032
  • 26
  • 132
  • 246