【问题标题】:Can operators be used as functions? (C++)运算符可以用作函数吗? (C++)
【发布时间】:2009-06-14 06:51:57
【问题描述】:

这与我提出的另一个问题相似,但是,我创建了一个表达式类,其工作方式如下:

expression<int, int> exp(10, 11, GreaterThan);
//expression<typename T, typename U> exp(T val1, U val2, oper op);
//where oper is a pointer to bool function(T, U)

其中 GreaterThan 是先前定义的函数。我想知道为什么我不能这样做:

expression<int, int> exp(10, 11, >);

特别是当 > 被重载为

bool operator>(int a, int a){return (a > b);}

与 GreaterThan 相同:

bool GreaterThan(int a, int b){return (a > b);}

一个返回 bool 并接受两个参数的函数。

【问题讨论】:

    标签: c++ operator-overloading function-pointers


    【解决方案1】:

    我不确定这是否是您要问的,但 C++ 标准库为许多 C++ 运算符提供函数对象,在标头 &lt;functional&gt; 中声明。这包括std::plus (+)、std::minus (-)、std::multiplies (*)、std::divides (/)、std::modulus (%)、std::negate (一元 -)、std::equal_to (= =)、std::not_equal_to (!=)、std::less (std::greater (>)、std::less_equal (std::greater_equal (>=)、std::logical_and (&&)、@987654335 @ (||), std::logical_not (!)

    所以也许你只是想要

    expression<int, int> exp(10, 11, std::greater<int>());
    

    【讨论】:

      【解决方案2】:

      代替:

      expression<int, int> exp(10, 11, >);
      

      你可以这样做:

      expression<int, int> exp(10, 11, operator>);
      

      可以,因为它不适用于整数。但它适用于您将重载的其他类型或运算符。

      您重载的运算符是普通函数,因此实际上您是在使用函数指针。

      【讨论】:

        【解决方案3】:

        您不能写出以下内容:

        bool operator>(int a, int a){return (a > b);}
        

        C++ 不允许为内置类型重载运算符。请重新编写您的问题,并特别给出表达式模板的实际代码。

        【讨论】:

          【解决方案4】:

          Neil 是对的,这不适用于内置类型。至少其中一个参数必须是“正式类类型”。另一个问题是

          expression<int, int> exp(10, 11, >);
          

          不是编译器喜欢你写的。相反,您可以使用类似以下代码的内容

          class A
          {
          
          };
          class B
          {
          
          };
          typedef bool (*oper)(A& a, B& b);
          bool operator>(A& a, B& b)
          {
            return false;
          
          }
          bool func(A&a, B& b, oper op)
          {
          
          }
          

          然后在你的代码中

            A a;
            B b;
            func(a, b, operator>);
          

          【讨论】:

            【解决方案5】:

            例如 + 运算符的类型

            int (__thiscall Integer::*)(int value)
            

            对于算子函数

            int Integer::operator + (int i)
            

            要传递运算符函数,您只需这样做:

            Integer a(10), b(20);
            add(a, b, &Integer::operator +);
            

            要使用它,请执行以下操作:

            (a.*functionPtr)(b);
            

            【讨论】:

            • 只是一个与运算符重载的使用无关的示例类。
            猜你喜欢
            • 2022-01-07
            • 2011-10-14
            • 2020-03-03
            • 2019-10-10
            • 2018-01-21
            • 1970-01-01
            • 2010-12-03
            • 2011-05-29
            相关资源
            最近更新 更多