2010-11-11 57 views
19

下面的代碼工作正常的std ::綁定重載

#include <functional> 

using namespace std; 
using namespace std::placeholders; 

class A 
{ 
    int operator()(int i, int j) { return i - j; } 
}; 

A a; 
auto aBind = bind(&A::operator(), ref(a), _2, _1); 

這不

#include <functional> 

using namespace std; 
using namespace std::placeholders; 

class A 
{ 
    int operator()(int i, int j) { return i - j; } 
    int operator()(int i) { return -i; } 
}; 

A a; 
auto aBind = bind(&A::operator(), ref(a), _2, _1); 

我曾嘗試與語法玩弄嘗試和明確解決哪些功能我想在到目前爲止沒有運氣的代碼。如何編寫綁定行以選擇使用兩個整數參數的調用?

+5

'A ::運算符()'並不是指單一功能,但一個家庭的功能:我認爲你必須施展才能「選擇」正確的過載。由於我不熟悉C++ 0x,因此我沒有將其驗證爲答案,我可能不知道更優雅的解決方案。 – icecrime 2010-11-11 21:40:24

回答

37

你需要一個投來澄清對重載函數:

(int(A::*)(int,int))&A::operator() 
+0

謝謝,讓它工作。 – bpw1621 2010-11-12 20:02:50

7

如果你有C++ 11提供你應該更喜歡在lambda表達式的std ::綁定,因爲它通常會導致代碼的可讀性:

auto aBind = [&a](int i, int j){ return a(i, j); }; 

相比

auto aBind = std::bind(static_cast<int(A::*)(int,int)>(&A::operator()), std::ref(a), std::placeholders::_2, std::placeholders::_1);