是否可以覆盖运算符
Is it possible to override operators?
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
中,您需要改用 <<
运算符。
相关文章:
- 为什么同时覆盖全局新运算符和特定于类的运算符不是模棱两可的行为?
- 为什么无法覆盖涉及第三方代码的模板类的运算符<<?
- 用std::string覆盖[]运算符
- 我想覆盖运算符'='但是在重载之后,运算符没有将正确的信息传递给对象
- c++ 中的运算符覆盖 = 运算符
- 如何在二叉树类中正确覆盖运算符<<?
- 使用运算符覆盖排序没有得到我想要的
- <<运算符覆盖使用 g++ 而不是窗口编译
- C++运算符删除覆盖并不总是使用
- Openfoam C++ 运算符和覆盖
- 覆盖 CAST 运算符(我认为它被称为向下转换)
- 无法覆盖C++中纯抽象类中的运算符删除/新建
- 对运算符删除覆盖的工作方式感到困惑
- 运算符 = 覆盖 c++
- 运算符覆盖 - 何时使用好友
- C++运算符覆盖 - 为什么首选朋友
- 初始化对象后,如何使用赋值运算符覆盖C++中的类对象
- Realloc 和全球本地新建/删除运算符覆盖
- unordered_multimap用法和运算符覆盖
- 特定预期模式的提取运算符覆盖