c++ - boost::bind 在存储时不保存部分参数

标签 c++ templates boost boost-bind

我正在尝试进行 boost::bind 调用并在 boost::function 中保存传递参数的值,我偶然发现了我无法解释的情况:

#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <memory>
#include <iostream>

template <class T>
using callback = boost::function<void (int, std::shared_ptr<T>)>;

class work
{
public:
    int value;
};


void job_callback(int v, std::shared_ptr<int> work)
{
    *work = v;
}

int main()
{
    std::shared_ptr<int> a(new int(10));
    boost::bind(job_callback, _1, a)(1); // compiles and works with 1 arg, *a is 1
    callback<int> call = boost::bind(job_callback, _1, a); // compiles
    call(2, a); // compiles and works with 2 args, *a is 2

    call(3); // does not compile with 1 arg

    return 0;
}

我不明白为什么boost::bind(job_callback, _1, a)(1)有效,即使只向结果仿函数提供了一个参数 - 因此第二个参数被传递 - 但是 call(3)没有编译并出现以下错误:

/usr/include/boost/function/function_template.hpp:761:17: note: boost::function2<R, T1, T2>::result_type boost::function2<R, T1, T2>::operator()(T0, T1) const [with R = void; T0 = int; T1 = std::shared_ptr<int>; boost::function2<R, T1, T2>::result_type = void]
/usr/include/boost/function/function_template.hpp:761:17: note:   candidate expects 2 arguments, 1 provided

boost::bind 的返回类型不叫boost::function<void (int, shared_ptr<int>)>但是其他东西,存储第二个参数值的东西?如果有,那是什么?

最佳答案

booststd {bind,function}产生同样的问题。我会用std供讨论的版本。我认为问题在于对函数对象的赋值。

callback<int> call = boost::bind(job_callback, _1, a); // compiles

它编译但不正确因为callback<int> == function<void (int,xxx)> .这不是正确的签名,因为两个参数之一已固定为 a .

但这里真正令人困惑的可能是为什么 function对象应该接受 bind当它不是正确的 arity 时的结果?我认为这可能与 std::bind 中引入的灵 active 有关处理额外的参数。我怀疑这也发生在 boost 中。但我对此不是 100% 确定。我一直不明白为什么 bind应该容忍不正确数量的参数。

正确的用法是

function<void (int)> call = std::bind(job_callback, _1, a); //also compiles

代码使用 std::{function,bind}

#include <functional>
#include <memory>
#include <iostream>
using namespace std;
using namespace std::placeholders;

template <class T>
using callback = std::function<void (int, std::shared_ptr<T>)>;

class work
{
public:
    int value;
};


void job_callback(int v, std::shared_ptr<int> work)
{
    *work = v;
}

int main()
{
    std::shared_ptr<int> a(new int(10));
    std::bind(job_callback, _1, a)(1); // compiles and works with 1 arg, *a is 1
    //callback<int> call = std::bind(job_callback, _1, a); // compiles
    function<void (int)> call = std::bind(job_callback, _1, a); //also compiles
    //call(2, a); // compiles and works with 2 args, *a is 2

    call(3); // does not compile with 1 arg

    return 0;
}

关于c++ - boost::bind 在存储时不保存部分参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21758572/

相关文章:

javascript - 链接标记在 Ember Js 中不起作用

c++ - Boost 或标准库是否提供了一种方法来检查转换是否无损?

c++ - 复制构造函数会在这里工作吗?

c++ - _di_IXMLNode 中不需要的 xmlns =""

C++协程用于使生成器永不停止

c++ - 类模板别名在生成的符号中不应该是可见的,是吗?

c++ - 使用通用函数指针参数化函数模板的巧妙方法

c++ - 如何计算点 o 填充/未填充矩形的距离

c++ - 为什么 autoconf 没有正确检测到 boost ?

C++ 操纵器?