开发者

how to make pointer to non-member-function?

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&, func开发者_JS百科P);

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?


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


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


"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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜