C++循环操作符
例如,我有一个求和:
x + y
我还想对相同的两个变量执行减法、乘法和除法:
x - y
x * y
x / y
依次循环所有四个运算符的最佳方式是什么?
我知道这在函数式编程语言中很容易做到,但在 C++ 中我不确定。
提前致谢。
I have a sum, for example:
x + y
I also want to perform subtraction, multiplication and division on the same two variables:
x - y
x * y
x / y
what's the optimum way of cycling through all four operators in turn?
I know this is easy to do in functional programming languages but in C++ I'm not sure.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
除了明显的“写出来”之外,还有一个想法:
Ideone 的示例。
Just one idea besides the obvious "writing them out":
Example at Ideone.
如果运算符是用户定义的,则在需要指向函数(成员)的指针时可以传递它们。对于基本类型,您可能需要编写包装器,如 Xeo 所示。
您还可以接受 std::binary_function 并使用 std::plus 等。
在 C++0X 中,使用 std::function 和 lambda 可以更轻松地实现这一点。
但显然,更准确地了解你想要实现的目标会有所帮助。
If the operators are user defined, they may be passed when pointer to functions (members) are expected. For basic types, you may need to write wrappers as Xeo showed.
You can also accept a std::binary_function and use std::plus and so on.
This is made easier in C++0X with std::function and lambda.
But obviously, knowing more precisely what you want to achieve would help.
也许这就是它的样子(类似于函数式编程语言):
Probably this is how it could looks like (similar to functional programming languages):