You have to make the difference between built-in operators and overloaded operators. Built-in operators are operators that have as operands only basic types (integers, booleans, floats, pointers).
E.g.:
int a = 9, b = 7;
a + b; <-- built-in plus operator
6 + 5; <-- built-in plus operator
C++ gives the possibility to define operators for user defined types (i.e. classes). std::string
is a class (defined by the library, but that doesn't matter). So if we write this:
std::string a = "asdf", b = "qwert";
a + b; <-- this is not built-in operator.
In order for the above to compile there has to be a declaration and definition of a plus operator that operates on two objects of type string. It happens that the standard library defines such operator: std::operator+(std::basic_string). So this:
std::string a = "asdf", b = "qwert";
a + b;
is actually this:
std::string a = "asdf", b = "qwert";
std::operator+(a, b); <-- call to overloaded operator (see this as a function call)
Built-in operators are not functions. Overloaded operators behave like functions.
Built-in operators have only basic types as operands and their functionality is defined by the standard (you cannot redefine what int + int
does).
Overloaded operators must have at least one operand of user-defined type.
Lets get to some practical examples:
template <class T, class Compare>
bool compare (T a, T b, Compare comp) {
return comp(a,b);
}
I've replaced your function pointer with a template parameter. So this can be a function pointer, a function reference or a function object.
What choices do you have to call this with T
as int
? Well you certainly can't have an operator passed for comp
. So you have to have a function or a function object (see link below).
// function
bool intCompareLess(int a, int b) {
return a < b;
}
compare(3, 5, intCompareLess);
// function object
class IntComparatorLess {
public:
// this is a function call operator overload
bool operator()(int a, int b) {
return a < b;
}
};
compare(3, 5, IntComparatorLess());
// or don't reinvent the wheel:
compare(3, 5, std::less<int>()); // std::less is somehow similar with IntComparatorLess
what if you call compare with T
as a user defined type
class MyClass {
public:
int x, y;
};
Now you have an extra option: define a operator and pass it as parameter:
bool operator<(MyClass c1, MyClass c2) {
if (c1.x == c2.x)
return c1.y < c2.y;
return c1.x < c1.x
}
MyClass a, b;
compare(a, b, (bool (*)(MyClass, MyClass))operator<);
usefull: C++ Functors - and their uses