c++ - 绑定(bind)并传递模板函数调用

标签 c++ templates stdbind

这不起作用: http://ideone.com/mUL5Y

我认为我在扣除该类型方面帮了它一点忙: http://ideone.com/mGfUj

也不行!我不明白为什么不。

我应该怎么做?

最佳答案

问题似乎是std::bind正在内部传递 Callable评估结果 (它实际上是一个 std::bind<> 类型)对象 c当你在这里第二次通过它时:

part2(std::bind(&Quux::part3<Callable>, this, 3, c))

它没有传递 std::bind 的未评估版本像你假设的对象。

因此,由于您的 f函数返回 void类型,c 的结果表达式在内部作为 void 传递类型,而不是未评估的可调用函数对象。因此,当您尝试调用 Callable对象 cQuux::part2 ,它又尝试评估调用 cQuux::part3 , 它不能将可调用对象作为第二个参数传递给 Quux::part3 ,因为它传递的类型实际上是 void类型,而不是可调用类型。

如需进一步引用,请参见此处:http://en.cppreference.com/w/cpp/utility/functional/bind

特别注意:

If std::is_bind_expression<T>::value==true (i.e., another std::bind() subexpression was used as an argument in the initial call to bind), then that bind-subexpression is invoked immediately and its result is passed to the function.

如果你想延迟评估以便它在你想要的时候发生,而不是在你通过 std::bind 时发生子表达式,您将不得不寻找其他方法,例如 lambda 或 std::function<>对象、仿函数或其他一些类对象类型,既可调用又可存储可在以后评估的状态。

关于c++ - 绑定(bind)并传递模板函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9694506/

相关文章:

c++ - 在计算所有可能路径问题时计算 nCr

c# - 从c++调用C# com对象,谁应该释放内存?

c++ - 当我用 libgcc 替换 libstdc++ 时,为什么我的 C++ 程序可以正确链接

django - 使用forloop.counter值作为Django模板中的列表索引

c++ - 在 C++ 中设计一个高性能的数值函数

c++ - 确定与 std::function<R(T1,T2)> 兼容的函数类型集的规则?

c++ - std::bind 应该需要移动构造函数吗?

c++ - 为什么 bind() 应该被弃用?

c++ - C++ 中的继承成本

c++ - 绑定(bind) std::function 错误