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

我是研究僧i 提交于 2019-12-22 11:14:54

问题


This is similar to another question I've asked, but, I've created an expression class that works like so:

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)

where GreaterThan is a previously defined function. And I am wondering why I can't do this:

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

particularily when > is overloaded as

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

which is identical to GreaterThan:

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

A function that returns bool and takes two arguments.


回答1:


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.




回答2:


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>());



回答3:


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.




回答4:


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



回答5:


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


来源:https://stackoverflow.com/questions/992320/can-operators-be-used-as-functions-c

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