bpw*_*621 24 c++ functional-programming std c++11
以下代码工作正常
#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 );
Run Code Online (Sandbox Code Playgroud)
事实并非如此
#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 );
Run Code Online (Sandbox Code Playgroud)
我已经尝试过使用语法来尝试明确地解析我想要的代码中哪个函数到目前为止没有运气.如何编写绑定行以选择带有两个整数参数的调用?
Jam*_*lis 43
你需要一个强制转换来消除重载函数的歧义:
(int(A::*)(int,int))&A::operator()
Run Code Online (Sandbox Code Playgroud)
sig*_*igy 17
如果你有C++ 11可用,你应该更喜欢lambdas over,std::bind因为它通常会导致代码更具可读性:
auto aBind = [&a](int i, int j){ return a(i, j); };
Run Code Online (Sandbox Code Playgroud)
相比
auto aBind = std::bind(static_cast<int(A::*)(int,int)>(&A::operator()), std::ref(a), std::placeholders::_2, std::placeholders::_1);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7499 次 |
| 最近记录: |