2010-11-11 37 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); 
相关问题