c ++使用模板类嵌套模板专业化

时间:2014-06-17 11:31:17

标签: c++ templates nested

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

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

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

2 个答案:

答案 0 :(得分:5)

您不能部分专门化功能模板,但您可以上课。 因此,您可以将实现转发给类,如下所示:

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

答案 1 :(得分:4)

如果声明

,则无法部分专门化某个功能
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

相关问题