Specialization of C ++ nested templates with template class

My problem is as follows. This is my method:

template<class T> T my_function(); 

These specializations work fine:

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

But this is not so:

one.

  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 an error message:

 too many template-parameter-lists 

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

+4
c ++ templates nested
source share
2 answers

You cannot partially specialize a function template, but you can for a class. Thus, you can redirect the implementation to the class as follows:

 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>()(); } 
+4
source share

You cannot partially specialize a function if you declare

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

and try calling the first with

 my_function<int>(); 

since partial specializations are not allowed for functions, these declarations will be contradictory (in fact, these are two different declarations, and what's worse: they both correspond to this instance).

What you can do is wrap your function in a class or structure 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

+3
source share

All Articles