user98188
user98188

Reputation:

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

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.

Upvotes: 3

Views: 466

Answers (5)

Nick Bedford
Nick Bedford

Reputation: 4435

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

Upvotes: -1

newacct
newacct

Reputation: 122439

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

Upvotes: 9

Oleg Zhylin
Oleg Zhylin

Reputation: 1310

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

Upvotes: 2

Nick Dandoulakis
Nick Dandoulakis

Reputation: 43110

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.

Upvotes: 6

anon
anon

Reputation:

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.

Upvotes: 3

Related Questions