3

I'm trying to pass an overloaded function pointer as shown below in the sample code.

class Sample
{
  uint32_t method(char* input1, double input2);
  uint32_t method(double input1);
}

template<class T, class... Args)
void processInput(T &&t, Args&&... a)
{
  std::packaged_task<uint32_t(Args...)> task(std::bind(t, a...));
  // other processing
}

// Caller invokes the below API
Sample* obj = new Sample();
processInput(static_cast<uint32_t(*)(double)>(&Sample::method), &*obj, 2.0f);

But this code doesn't compile. It keeps complaining that it can't determine which instance of overloaded function is intended. I referred several examples:

C++ overloaded method pointer

http://en.cppreference.com/w/cpp/language/static_cast

Can somebody help in pointing out what is going wrong here?

Community
  • 1
  • 1
pree
  • 2,297
  • 6
  • 37
  • 55
  • 3
    Shoudln't `static_cast` be `static_cast` as it is a member function? – NathanOliver Apr 29 '16 at 18:40
  • 1
    @pree Fix your typos (missing `;`, `)` instead of `>`). The function also does not return `double`. – LogicStuff Apr 29 '16 at 18:41
  • That was it! I didn't really understand the implementation of static_cast in function overloading and was doing it wrong! Thanks @NathanOliver & LogicStuff. – pree Apr 29 '16 at 18:53

1 Answers1

6

Once you fix the typos, the main problem is that you're trying to cast a member function pointer to a function pointer.

That is, the following is illegal:

static_cast<uint32_t(*)(double)>(&Sample::method)
error: invalid static_cast from type 
‘uint32_t (Sample::*)(double)  {aka unsigned int (Sample::*)(double)}’ 
to type 
‘uint32_t (*)(double) {aka unsigned int (*)(double)}’

The syntax for a member function pointer is

ReturnT(ClassT::*)(ArgTs);

So your cast would have to be:

static_cast<uint32_t(Sample::*)(double)>(&Sample::method)

Example:

#include <iostream>
#include <functional>

struct Sample
{
  uint32_t method(char* input1, double input2) { return 0; }
  uint32_t method(double input1) { return 0; }
};

template<class T, class... Args>
void processInput(T &&t, Args&&... a)
{
  auto task = std::bind(t, a...);
  (void)task;
}

int main()
{
    Sample* obj = new Sample();
    processInput(static_cast<uint32_t(Sample::*)(double)>(&Sample::method), obj, 2.0f);

    return 0;
}
Steve Lorimer
  • 27,059
  • 17
  • 118
  • 213