c++ nested template specialization with template class

一曲冷凌霜 提交于 2019-12-10 15:37:34

问题


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?


回答1:


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>()(); }



回答2:


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



来源:https://stackoverflow.com/questions/24262648/c-nested-template-specialization-with-template-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!