将std :: bind创建的对象传递给函数的正确方法是什么?

问题描述 投票:1回答:1

假设我想通过引用[f0]传递std::bind创建的功能对象:

void myCallback(int i, int j)
{
    std::cout << "toCall , i=" << i << " j=" << j;
}

void worker(std::function<void(int)> & callback)
{
    callback(111);
}

int main(int argc, char** argv)
{
    auto foo = std::bind(myCallback, std::placeholders::_1, 222);
    worker(foo);
}

无法编译

compiler error

但是,按价值传递有效:

void worker(std::function<void(int)> callback)
{
    callback(111);
}

[当我避免使用“ auto”而改为使用

std::function<void(int)> foo = std::bind(myCallback, std::placeholders::_1, 222);

它既可以通过引用也可以通过值传递。

Q1:为什么会这样?

Q2:将std::bind创建的对象传递给函数的“正确”方式或数据类型是什么?

c++ pass-by-reference functor auto stdbind
1个回答
0
投票
应该是:

void worker(std::function<void(int)> const& callback);

© www.soinside.com 2019 - 2024. All rights reserved.