Ali
Ali

Reputation: 231

How do you pass overload operator members of classes as function pointers?

For example, if I wanted to pass

ostream& std::ostream::operator << (int i);  

into a function such as

void func(ostream& (*out)(int), ...);

then how would I go about doing that?

Doing

func(std::ostream::operator << (int))

surely does not work and

typedef ostream& (*out)(int);
out o = std::ostream::operator << (int);
func(o);

throws a compile-time error when trying to assign o. So how does one point to overloaded operators? (casting to type out does not work in this situation either)


After playing around with the code, my question is now this: why is it that non-member, overloaded operators i.e

ostream& operator << (ostream&, classX) 

return a void* and not a pointer to a function?

If I do

typedef ostream& (*out)(ostream&,classX);

I can only make it

void* v = ostream& operator << (ostream&,classX);

and not

out o = ostream& operator << (ostream&,classX);

which prints the error messsage

190: error: invalid conversion from 'void*' to 'std::ostream& (*)(std::ostream&, classX)'

Upvotes: 3

Views: 730

Answers (2)

tahsmith
tahsmith

Reputation: 1723

I would simplify the assignment here. There is no need to specify the whole signature, since the correct overload can be inferred from the type on the left hand side.

#include <iostream>
using namespace std;

struct Foo
{
    int x;
};

ostream& operator<< (ostream &a, const Foo& b)
{
    return a << b.x;
}

typedef ostream& (*Func) (ostream &, const Foo&);

int main() {
    Func func = &operator<<;
    (*func)(cout, Foo{42});
}

Upvotes: 1

Manu343726
Manu343726

Reputation: 14184

Depend on how you have overloaded the operator.

The signature (The type of the pointer that points to) of a function is:

  • RETURN_TYPE(*)(PARAMETERS_TYPES) if its a global function.
  • RETURN_TYPE (CLASS_NAME::*)(PARAMETERS_TYPES) if its a member function.

If you have a function called f and a function that gets a pointer to a function as parameter, f is passed as follows:

  • g(f) if f is a global function.
  • g(&CLASS_NAME::f) if f is a member function of CLASS_NAME class.

Note that function pointers and member function pointers are not compatible.

So if your operator is overloaded as a member function, like operator+= you should use the second version. If not, you should use the first.

Upvotes: 3

Related Questions