如何在容器和类型上定义模板化的功能?
例如,重载插入运算符用于流送向量,列表或转发迭代器容器的所有元素:
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句