是否可以覆盖运营商?

时间:2014-09-17 00:38:52

标签: c++ c++11 c++14

template<typename T,typename F,typename R = typename std::result_of<F(T)>::type>
R operator>>(T t,F f){
  return f(t);
} 

int inc(int i){
  return i + 1;
}
struct foo{
  int i = 0;
};
void print_foo(foo f){
  std::cout<< f.i << std::endl;
}
int get_foo_i(foo f){
  return f.i;
}

int main()
{
  foo f{1};
  f >> print_foo;//works
  int i = f >> get_foo_i;//works
  int i2 = 5 >> inc;//invalid operants
  return 0;
}

我创建了自己的>>运算符,它就像一个管道。它适用于我的自定义类型,但它会打破已经有>>运算符的类型。

是否可以覆盖&gt;&gt;所有类型的全球运营商?也许我可以使用命名空间来做到这一点?

5 pipe::>> inc

1 个答案:

答案 0 :(得分:5)

您不能覆盖内置数据类型的运算符,仅适用于自定义类型。在您的示例中,要将5流式传输到foo,您需要覆盖<<运算符。

相关问题