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

时间:2018-09-07 09:08:27

标签: c++ stdbind

我想存储对std::function<int(int,int>>对象的回调。当我使用lambda时,它可以正常工作。但是,当我对成员函数使用std::bind时,它会编译错误。

有示例错误代码。

#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;
}

错误消息:

 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

代码链接:http://cpp.sh/9pm3c

1 个答案:

答案 0 :(得分:4)

您需要指出request.RequestUri.Scheme带有2个参数,请使用A::calc进行操作:

std::placeholders::X
相关问题