带有模板类的C ++嵌套模板专业化 [英] c++ nested template specialization with template class
本文介绍了带有模板类的C ++嵌套模板专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的问题如下. 这是我的方法:
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>();
...
但是这些不是:
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
所以我的问题是: 如何使用模板类专门化模板?
推荐答案
您不能部分专用于功能模板,但可以用于类. 因此,您可以将实现转发给以下类:
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>()(); }
这篇关于带有模板类的C ++嵌套模板专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文