2016-04-29 117 views
2

我想傳遞重載函數指針,如下面的示例代碼中所示。C++重載函數指針模糊

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

可在指出別人的幫助是怎麼回事錯在這裏?

+3

Shoudln't'的static_cast <雙(*)(雙)>'是'的static_cast ',因爲它是一個成員函數? – NathanOliver

+1

@pree修復你的拼寫錯誤(缺少';',''''而不是'>')。該函數也不返回'double'。 – LogicStuff

+0

就是這樣!我真的不明白static_cast在函數重載中的實現,並且做錯了!謝謝@NathanOliver&LogicStuff。 – pree

回答

4

修復錯別字後,主要問題是您試圖將成員函數指針強制轉換爲函數指針。

也就是說,下面是非法的:

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