【问题标题】:How to std::bind a smart pointer return method?如何 std::bind 智能指针返回方法?
【发布时间】:2015-12-14 22:23:48
【问题描述】:

所以我的Bar 类中有这个方法:

std::shared_ptr<sf::Sprite> Bar::getStuff() const
{
   //...
}

我有我的回调 typedef:

typedef std::function<void()> Callback;

void Foo::registerCallback(const Callback& callback)
{
    //...
}

现在我想在这个方法上使用std::bind,比如:

Foo foo;
Bar bar; //I create an instance of an Bar, called bar. 

foo.registerCallback(std::bind(&Bar::getStuff, std::ref(bar))); //<--- ERROR!!!!

错误:

error C2562: 'std::_Callable_obj<std::_Bind<true,std::shared_ptr<sf::Sprite>,std::_Pmf_wrap<std::shared_ptr<sf::Sprite> (__thiscall Bar::* )(void) 

如果我想使用 void 方法,没关系。但我需要使用getStuff() 方法,它会将smart pointer 返回到 sf::Sprite 事物。

我怎样才能做到这一点?

【问题讨论】:

  • 试试std::bind(&amp;Bar::getStuff, &amp;bar),IIRC,std::ref不能在INVOKE中使用
  • @PiotrSkotnicki bind 解开 reference_wrappers,独立于 INVOKE。 (无论如何,LWG 2219INVOKE 与他们合作。)
  • 这是哪个版本的 MSVC?
  • VS C++ 2012 与编译器:“Microsoft Visual C++ Compiler Nov 2012 CTP (v120_CTP_Nov2012)”
  • @T.C.哦,原来如此,谢谢

标签: c++ c++11 smart-pointers stdbind


【解决方案1】:

鉴于您使用的是 c++11,为什么不用 lambda?

foo.registerCallback([&bar]() { bar.getStuff(); });

【讨论】:

  • @Nicol,我将其保留为副本,因为通常您希望保证生命周期(因为它是一个回调。)所以假设 barshared_ptr 中 - 这将是正确的型号...
  • 是的,但是他的代码使用std::ref 明确地绑定了它。如果他想要一份副本,他就会把价值放在那里。显然,使用参考是一个坏主意,但这就是他的要求。
【解决方案2】:

std::bind works with std::reference_wrapper。您的错误来自您调用它的方式。 Bar::getStuff 返回您尝试丢弃的内容。你只能在丢弃表达式和语句中丢弃东西。

解决方案

template<class Callable>
auto discard_callable(Callable&& callable)
{ return [=]() { (void) callable(); }; }

你可以这样使用它:

foo.registerCallback(discard_callable(
    std::bind(&Bar::getStuff, std::cref(bar))
));

MCVE

#include <functional>
#include <string>

struct Butler
{
    std::string say() const { return "Welcome home, Sir."; }
};

template<class Callable>
auto discard_callable(Callable&& callable)
{ return [=]() { (void) callable(); }; }

int main()
{
    Butler igor;
    std::function<void()> welcome = discard_callable(std::bind(&Butler::say, std::ref(igor))); // error without discard
    welcome();
}

Live demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多