我可以根据算术运算写关系运算符吗? [英] Can I Write Relational Operators in Terms of Arithmetic Operations?

查看:61
本文介绍了我可以根据算术运算写关系运算符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个相当复杂的功能:

So I have a fairly complex function:

template <typename T>
void foo(const int param1, const int param2, int& out_param)

给出int barconst int arg1const int arg2,将使用以下任一方法调用该函数:foo<plus<int>>(arg1, arg2, bar)foo<minus<int>>(arg1, arg2, bar)

Given int bar, const int arg1, and const int arg2 the function will be called with either: foo<plus<int>>(arg1, arg2, bar) or foo<minus<int>>(arg1, arg2, bar)

内部函数相当复杂,但是我根据作为模板参数传递的函子的类型来做不同的关系运算符.

Internally the function is rather complex but I am doing different relational operators based on the type of functor that was passed as a template parameter.

对于plus,我需要这样做:

  1. arg1 > arg2
  2. bar > 0
  3. bar > -10
  1. arg1 > arg2
  2. bar > 0
  3. bar > -10

对于minus,我需要这样做:

  1. arg1 < arg2
  2. bar < 0
  3. bar < 10
  1. arg1 < arg2
  2. bar < 0
  3. bar < 10

请注意,10在两个 3 中没有相同的符号.我目前正在通过传递第二个模板参数(lessgreater)来解决所有这些问题.但是我当时认为将这些关系写为算术运算可能更有意义.甚至有可能吗?还是我需要使用第二个模板参数?

Note that 10 does not have the same sign in both 3s. I am currently solving all this by passing a second template parameter (less or greater.) But I was thinking it might make more sense to write these relations as arithmetic operations. Is that even possible, or do I need to take the second template parameter?

推荐答案

T{}(0, arg1) > T{}(0,arg2);
T{}(0, bar) > 0;
T{}(0, bar) > -10;

当且仅当-a < -b时,基本思想是a > b.而plus(0,a)==aminus(0,a)==-a.

The basic idea is a > b if and only if -a < -b. And plus(0,a)==a while minus(0,a)==-a.

最后一个是棘手的,因为我们要更改<的顺序和符号.幸运的是,他们取消了:

The last one is tricky, as we want to change the order of < and the sign. Luckily they cancel:

假设我们想要一个在加号情况下为-10而在减号情况下为10的常数.然后

Suppose we want a constant that is -10 in the plus case, and 10 in the minus case. Then

plus(0,-10)

-10

minus(0,-10)

10.

所以我们得到:

T{}(0, bar) > T{}(0, T{}(0,-10))

在加号的情况下,rh是0+0+-10,又名-10.

in the plus case, the rhs is 0+0+-10, aka -10.

在减号情况下,这是0-(0-(-10)),又名-10.

In the minus case, this is 0-(0-(-10)), aka -10.

所以简写为:

T{}(0,bar) > -10

它应该可以工作.

这篇关于我可以根据算术运算写关系运算符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆