Calling overloaded function using templates (unres

2019-05-15 05:41发布

问题:

Possible Duplicate:
How to get the address of an overloaded member function?

I have a function overloaded for a set of types in a class inheritence heirarchy, e.g. Share with FutureShare and OptionShare derived.

virtual unsigned rank() const
{ return getValue(*this, rank_, &ShareUtils::getRank); } 

template<typename TShare , typename TMember, typename TGetMemberFunc >
TValue& getValue(const TShare& share, boost::optional<TMember>& member, TGetMemberFunc func)
{
    if(!member)
    {
        member.reset(func(share));
    }
    return *member;
}

boost::optional<unsigned> rank_;

//-------

static unsigned ShareUtils::getRank(const Share& share) { //... } 
static unsigned ShareUtils::getRank(const OptionShare& option) { //... } 
static unsigned ShareUtils::getRank(const FutureShare& future) { //... } 

When compiling I get the following error:

Share.h: In member function `virtual unsigned int Share::rank() const':
Share.h:25: error: no matching function for call to `Share::getValue(const Share&, boost::optional<unsigned int>&, <unresolved overloaded function type>) const'

How do I correctly call the overloaded function? I figured TShare would resolve the overload when calling func?

EDIT I forgot to mark the overloaded functions static.

回答1:

This fails to compile because ShareUtils::getRank does not refer to a single function but to a family of functions (there are several signatures for this name).

You want to cast to function pointer to suppress the ambiguity, which means that you must know from the rank function which getRank should be called (which should not be a problem in your case) :

virtual unsigned rank() const
{ return getValue(*this, rank_, (unsigned (ShareUtils::*)(const Share&)) &ShareUtils::getRank); }