std::bind 重载解析

2022-01-02 00:00:00 functional-programming c++ c++11 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 );

我已经尝试使用语法来尝试并明确地解决我想要的代码中的哪个函数,到目前为止,如果没有运气就无法工作.如何编写绑定行以选择采用两个整数参数的调用?

I have tried playing around with the syntax to try and explicitly resolve which function I want in the code that does not work without luck so far. How do I write the bind line in order to choose the call that takes the two integer arguments?

推荐答案

你需要一个强制转换来消除重载函数的歧义:

You need a cast to disambiguate the overloaded function:

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

相关文章