gpt4 book ai didi

c++ - 如何绑定(bind)传递未指定调用包装器的成员函数模板

转载 作者:可可西里 更新时间:2023-11-01 18:36:02 26 4
gpt4 key购买 nike

我尝试使用 VC11 和 g++ 4.7.2 编译以下示例:

#include <functional>

class X {
public:
template <typename T>
explicit X(T t)
{
std::bind(&X::invoke<T>, this, t)();
}
private:
template <typename T>
void invoke(T t)
{
t();
}
};

class Y {
public:
void foo() {
//...
}
};


int main() {
Y y;
X x(std::bind(&Y::foo, &y));
return 0;
}

但它以错误结束。我不确定粘贴整个编译器输出是否合理,但一般来说

vc11 说:

error C2664: 'void std::_Pmf_wrap::operator ()(_Farg0 &,_V0_t) const' : cannot convert parameter 3 from 'void' to 'std::_Bind,Y *,std::_Nil,std::_Nil,std::_Nil,std::_Nil,std::_Nil,std::_Nil>' c:\program files (x86)\microsoft visual studio 11.0\vc\include\functional 1152 1 ConsoleApplication1 (Microsoft Visual C++ Compiler Nov 2012 CTP)

和 g++:

Compilation finished with errors:
source.cpp: In instantiation of 'X::X(T) [with T = std::_Bind(Y*)>]':
source.cpp:28:33: required from here
source.cpp:8:9: error: no match for call to '(std::_Bind_helper(Y*)>), X* const, std::_Bind(Y*)>&>::type {aka std::_Bind(Y*)>)>(X*, std::_Bind(Y*)>)>}) ()'

有没有办法解决这个问题。保存主要思想对我来说非常重要 - 一个可以用任何可调用对象(函数对象、函数指针或 std::bind() 函数返回的调用包装器)实例化的类。

如果有人能提供帮助,我将不胜感激。

附言如果我创建 X 的实例并传递函数对象或函数指针,它就会编译。

最佳答案

我认为他们在将 boost::bind 引入 std::bind 时省略了一个重要的部分,即 boost::protect()。您的代码可以修复如下:

#include <boost/bind/protect.hpp>
// ...
X x(boost::protect(std::bind(&Y::foo, &y)));

或者,或者:

template <typename T>
explicit X(T t)
{
auto tt = boost::protect(t);
auto f = std::bind(&X::invoke<decltype(tt)>, this, tt);
f();
}

参见 http://www.boost.org/doc/libs/1_53_0/libs/bind/bind.html

Although the first argument is, by default, not evaluated, all other arguments are. Sometimes it is necessary not to evaluate arguments subsequent to the first, even when they are nested bind subexpressions. This can be achieved with the help of another function object, protect, that masks the type so that bind does not recognize and evaluate it. When called, protect simply forwards the argument list to the other function object unmodified.

The header boost/bind/protect.hpp contains an implementation of protect. To protect a bind function object from evaluation, use protect(bind(f, ...)).


即将到来Effective C++11: Content and Status Scott Meyers 将推荐 prefer lambdas to std::bind。在 C++11 中,您可以简单地执行以下操作:

template <typename T>
explicit X(T t)
{
auto f = [t, this]() { this->invoke(t); };
f();
}
// ...

X x([&y](){ y.foo(); });

关于c++ - 如何绑定(bind)传递未指定调用包装器的成员函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15115468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com