c++嵌套模板专门化与模板类

c++ nested template specialization with template class

本文关键字:专门化 c++ 嵌套      更新时间:2023-10-16

我的问题如下这是我的方法:

template<class T>
T my_function();

这些专门化工作正常:

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

但是这些没有:

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

我得到错误:

too many template-parameter-lists

我的问题是:如何用模板类专门化模板?

不能部分专门化函数模板,但可以专门化类。因此,您可以将实现转发到一个类,如下所示:

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

如果声明

,则不能部分特化函数
template<class T>
T my_function() {
    ....
}
template<class T>
std::list<T> my_function() {
    ....
}

并尝试用

调用第一个
my_function<int>();

由于函数不允许部分专门化,所以这些声明将会冲突(它们实际上是两个不同的声明,更糟糕的是:它们都匹配那个实例化)。

你能做的是将你的函数包装成一个类或一个结构体,可以处理它的部分特化:

#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