Can operators be used as functions? (C++)

我只是一个虾纸丫 提交于 2019-12-05 23:27:43

Instead of:

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

you could do this:

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

You could because it doesn't work for integers. But it will work for other types or operators that you will overload.

The operators that you overload are normal functions, so actually you are playing with function pointers.

I'm not sure if this is what you are asking, but the C++ standard library provides function objects for many of C++'s operators, declared in the header <functional>. This includes std::plus (+), std::minus (-), std::multiplies (*), std::divides (/), std::modulus (%), std::negate (unary -), std::equal_to (==), std::not_equal_to (!=), std::less (<), std::greater (>), std::less_equal (<=), std::greater_equal (>=), std::logical_and (&&), std::logical_or (||), std::logical_not (!)

So maybe you just want

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

You cannot have written the following:

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

C++ does not allow overloading of operators for the built-in types. Please re-write your question, and particularly give the actual code for the expression template.

Neil is right, this wouldn't work for built-in types. At least one of the parameters must be "formal class type". Another problem is that

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

is not what compiler likes you to write. Instead you can use something like the following code

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)
{

}

and then in your code

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

The + operator for example is of type

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

for the operator function

int Integer::operator + (int i)

To pass the operator function you simply do this:

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

To use it do this:

(a.*functionPtr)(b);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!