简体   繁体   English

如何将std :: bind结果存储到std :: function

[英]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. 我想将回调存储到std::function<int(int,int>>对象。当我使用lambda时,它可以正常工作。但是当我使用std::bind到成员函数时,它会编译错误。

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 代码链接: http : //cpp.sh/9pm3c

您需要指出A::calc接受2个参数,使用std::placeholders::X可以做到:

std::function<int(int,int)> callback = std::bind(&A::calc, this, std::placeholders::_1,std::placeholders::_2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM