我正在尝试传递一个重载的函数指针,如下面的示例代码所示。
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);
但是这段代码没有编译。它一直在抱怨它无法确定哪个重载函数实例。我提到了几个例子:
http://en.cppreference.com/w/cpp/language/static_cast
有人可以帮忙指出这里出了什么问题吗?
答案 0 :(得分:6)
修复拼写错误后,主要问题是您正在尝试将成员函数指针强制转换为函数指针。
即,以下是非法的:
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;
}