views:

102

answers:

3

if i have for example class A which contains the functions:

//this is in A.h
friend const A operator+ (const A& a,const A& b);
friend const A operator* (const A& a,const A& b);

which is a global (for my understanding). this function implemented in A.cpp.

now, i have class B which also contains the functions, and the member:

//this is in B.h
friend const B operator+ (const B& a,const B& b);
friend const B operator* (const B& a,const B& b);
A _a;

instead of using two seperate methods, i want to create single method in B.h:

static const B Calc(const B&, const B&, funcP);

which implemented in B.cpp and funcP is typedef to the pointer to the function above:

typedef const A (*funcP) ( const A& a, const A& b);

but when i tried to call Calc(..) inside the function i get this error: "unresolved overloaded function type". i call it this way:

friend const B operator+ (const B& a,const B& b){
    ...
    return B::Calc(a,b, &operator+);
}

what am i doing wrong?

+2  A: 

Overloaded functions are usually resolved based on the types of their arguments. When you make a pointer to a function this isn't possible so you have to use the address-of operator in a context that is unambiguous.

A cast is one way to achieve this.

static_cast<funcP>(&operator+)
Charles Bailey
or.nomore
Charles Bailey
NewDouble is my A, sorry for the mix
or.nomore
but i want to use the operator+ of class A
or.nomore
Charles Bailey
A: 

Don't do that. It's ugly, error-prone, and hard to understand and maintain.

This is what templates were invented for:

template< typename T >
static T Calc(const T& lhs, const T&, funcP rhs)
{
  return lhs + rhs;
}

(Note that I removed the const from the function's return type. Top-level const on non-referencing types makes no sense.)

sbi
sbi: `const` is perfectly find and often encouraged on function return types. It only makes no difference if the return type is of non-class object type.
Charles Bailey
but i don't realy understand how it can help me. do you mean turning class B to template calss?
or.nomore
@or.nomore: I didn't turn `B` into a class template, but `Calc` into a function template. It can now be instantiated with both `A` and `B`, and automatically picks up the right overload of `operator+`.
sbi
@sbi: but the T is always of type B
or.nomore
@or.nomore: Then why would you ever want to use `operator+(A,A)`??
sbi
@Charles Bailey: Could you explain? What's the advantage? Clients could always create non-`const` copies anyway, no? The only case I can think of where it'd matter is in restricting anonymous objects (e.g. `Calc(...).foo()` wouldn't work if `foo()` isn't `const`, although `T(Calc(...)).foo()` would be fine).
jamesdlin
A: 

"which is a global (for my understanding)."

not for microsoft c at least "A friend function defined in a class is not supposed to be treated as if it were defined and declared in the global namespace scope" from ms visual c++ help

frag