views:

262

answers:

5

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.

+3  A: 

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.

anon
+6  A: 

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.

Nick D
+2  A: 

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>);
Oleg Zhylin
+7  A: 

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>());
newacct
A: 

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);
Nick Bedford
What is this magical `Integer` type you speak of?
GMan
Just an example class that wasn't to unrelated to the use of operator overloads.
Nick Bedford