Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ nested template specialization with template class

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?

like image 813
eddy Avatar asked Jun 17 '14 11:06

eddy


1 Answers

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>()(); }
like image 115
Jarod42 Avatar answered Sep 30 '22 02:09

Jarod42