是否可以覆盖运算符

Is it possible to override operators?

本文关键字:运算符 覆盖 是否      更新时间:2023-10-16
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;
}

我创建了自己的>>运算符,它的作用类似于管道。它适用于我的自定义类型,但它会在已经具有>>运算符的类型上中断。

是否可以全局覆盖所有类型的>>运算符?也许我可以用命名空间来做到这一点?

5 pipe::>> inc

不能重写内置数据类型的运算符,只能重写自定义类型的运算符。 在您的示例中,要将5流式传输到 foo 中,您需要改用 << 运算符。