C++重载函数指针歧义

C++ overloaded function pointer ambiguity

我正在尝试传递重载函数指针,如下面的示例代码所示。

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

但是这段代码无法编译。它一直抱怨它无法确定要使用哪个重载函数实例。我参考了几个例子:

C++ overloaded method pointer

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

有人可以帮忙指出这里出了什么问题吗?

一旦你修正了拼写错误,主要问题是你试图将成员函数指针转换为函数指针。

即以下是非法的:

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)}’

成员函数指针的语法是

ReturnT(ClassT::*)(ArgTs);

所以你的演员必须是:

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

示例:

#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;
}