3

I want to store a callback to a std::function<int(int,int>> object. When I use lambda, it works fine. But when I use std::bind to a member function, it compiled error.

There is the sample error code.

#include <functional>
#include <iostream>

using namespace std;

class A
{
public:
    void foo()
    {
        std::function<int(int,int)> callback = std::bind(&A::calc, this);
        // std::function<int(int,int)> callback = [this](int a, int b) { return this->calc(a, b); }; // lambda works fine
        int r = callback(3, 4);
        cout << r << endl;

    }

    int calc(int b, int c) { return b + c; }
};

int main()
{
    A a;
    a.foo();
    return 0;
}

error message:

 In member function 'void A::foo()':
12:72: error: conversion from 'std::_Bind_helper<false, int (A::*)(int, int), A*>::type {aka std::_Bind<std::_Mem_fn<int (A::*)(int, int)>(A*)>}' to non-scalar type 'std::function<int(int, int)>' requested

code link: http://cpp.sh/9pm3c

Alexander Chen
  • 417
  • 3
  • 17
  • The `std::function` is used to store the callable object, so the others can set the variable. So auto is not a acceptable option. – Alexander Chen Sep 07 '18 at 09:11
  • btw there is no advantage of `std::bind` over a lambda, other than being more complicated to use. There are some rare cases where a lambda wont help but you need bind, though i never encountered one – 463035818_is_not_an_ai Sep 07 '18 at 09:12
  • You can do that directly, without the `bind`: `std::function callback(&A::calc, this);`. – Pete Becker Sep 07 '18 at 11:25

1 Answers1

5

You need to indicate that A::calc takes 2 parameters, use std::placeholders::X to do it:

std::function<int(int,int)> callback = std::bind(&A::calc, this, std::placeholders::_1,std::placeholders::_2);
rafix07
  • 20,001
  • 3
  • 20
  • 33