代码如下:
#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
#include <string>
#include <string.h>
#include <iomanip>
using namespace std;
namespace test
{
template<typename T>
istream & operator >> ( istream & in, T & ContainerT )
{
while( in )
{
typename T::value_type val;
std::operator >> ( in, val );
if ( in )
{
ContainerT.push_back( val );
}
}
return in;
}
}
int main( )
{
//这样编译不报错
list<string> list_str;
test::operator >> ( cin, list_str );
//这样写就编译报错了
list<int> list_int;
test::operator >> ( cin, list_int );
return 0;
}
求教要怎么改写代码,才能让我重载的>>操作符对任何容器类型都能用呢
方案推荐指数:20
std::operator >> ( in, val );
改成
using std::operator>>;
in >> val ;
改成
using std::operator>>;
in >> val ;
方案推荐指数:20
我也研究了半天, 到现在才弄明白:
对于内置类型的来说, operator>> 函数是istream类的成员.
对于类类型来说, 由于不能修改istream类, 所以只能定义全局operator>>函数.
所以, 对于内置类型来说, 调用全局的就不匹配.
对于类类型来说, 调用istream的成员函数也不匹配.
唯一相同的就是通过运算符的方法调用.