C++嵌套模板特化与模板类

5
我的问题如下。 这是我的方法:
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> >();

I get the error:

too many template-parameter-lists

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

1
你想对一个函数模板进行部分特化。在C++中这是不可能的。 - Constructor
2个回答

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接