c++嵌套模板专门化与模板类
c++ nested template specialization with template class
我的问题如下这是我的方法:
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 相关文章:
- 是否可以对零模板参数进行模板专门化
- 尝试根据类中 typedef 的存在来专门化模板函数
- 如何基于模板化类的基类专门化成员函数
- 如何为指向复杂值的迭代器专门化算法?
- 专门化模板覆盖函数/避免对象切片
- 我能否根据其运算符()的签名专门化可变参数模板参数
- 如何使用模板化类专门化模板化函数?
- 线程 std::调用未知类型,无法专门化函数错误
- 输入两个不专门化大小的矩阵
- 如何在模板类中专门化赋值运算符?
- 如何专门化容器和枚举的模板
- Clang拒绝类模板的嵌套类仅通过专门化定义的代码是正确的吗
- 取消专门化C++模板参数
- SFINAE的变分变量模板专门化
- 如何在编译时专门化大型模板函数中的小部分
- 如何在c++运算符()中专门化调用模板
- 模板函数,其中一个参数需要专门化,而另一个不需要
- 如何专门化字符串数组的模板?
- 如何专门化模板
- 如何避免为模板化迭代器的每个可能的实例化专门化iterator_traits?