Alexander Chen
Alexander Chen

Reputation: 507

How to store std::bind result to std::function

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

Upvotes: 3

Views: 2388

Answers (1)

rafix07
rafix07

Reputation: 20938

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);

Upvotes: 5

Related Questions