如何在容器和类型上定义函数模板?
例如,重载插入运算符以流式传输 vector 、列表或前向迭代器容器的所有元素:
using namespace std;
#include <iostream>
#include <vector>
#include <list>
//...
//...the second argument is a container template-ed on type T
//...
template <typename T,template <typename U> class C>
ostream&
operator<<
(ostream& p_os,const C<T>& p_c)
{
for(typename C<typename T>::const_iterator cit=p_c.begin();cit!=p_c.end();++cit)
{
p_os.operator<<(*cit);
}
return p_os;
}
int
main
()
{
vector<int> v;
cout << v << endl;
list<int> l;
cout << l << endl;
return 0;
}
这不能在 g++ 4.9 上编译。怎么了?它是怎么做到的?
最佳答案
为什么不直接将容器类型作为模板参数传递,并从中找出元素类型呢?在您的示例代码中,您甚至不需要元素类型:
template <typename C>
ostream&
operator<<
(ostream& p_os,const C& p_c)
{
typedef typename C::value_type element_type; // if needed
for(typename C::const_iterator cit=p_c.begin();cit!=p_c.end();++cit)
{
p_os.operator<<(*cit);
}
return p_os;
}
(尽管在没有一些 enable_if
技巧的情况下将它用于像这样的全局函数可能是不明智的,因为否则它会匹配任何参数。)
编辑:例如,您可以尝试将其限制为具有嵌套 value_type
(所有容器都有)的类:
template <typename C, typename T = typename C::value_type>
ostream&
operator<<
(ostream& p_os,const C& p_c)
关于c++ - 模板类作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27336120/