【问题标题】:How std::bind increases number of arguments passed to a function?std::bind 如何增加传递给函数的参数数量?
【发布时间】:2016-08-06 21:45:56
【问题描述】:

我在看书,代码如下:

mActionBinding[Fire].action = derivedAction<Aircraft>(
std::bind(&Aircraft::fire, _1));

发送到派生动作的参数,将在两个之后发送。

template<typename GameObject, typename Function>derived action function 
std::function<void(SceneNode&, sf::Time)> derivedAction(Function fn) 
{
    return [=](SceneNode& node, sf::Time dt) expression 
    {
        assert(dynamic_cast<GameObject *>(&node) != nullptr);

        fn(static_cast<GameObject &>(node), dt);
    };
}

飞机类的火灾声明是这样的:

class Aircraft:public SceneNode
{
public:
    void fire()
};

我已经阅读了一些关于 std::bind 的文章,但老实说我还没有见过这样的东西。这要复杂得多。

让我整理一下我的问题:

1-根据我的阅读,这个 std::bind 有三个参数!成员函数、隐式类名和_1。是真的吗?这是否意味着,当我们在derivedAction 中调用它时,而不是static_cast&lt;gameObject &amp;&gt;(node),将发送“this”给它?

2-fire 根本没有参数!(除了隐含的 this),那么为什么 _1 没有给我们错误呢?以及如何将“dt”发送给它?

我有点困惑,参考提供了简单使用的示例,有关std::bind 的任何其他信息,将不胜感激。

【问题讨论】:

  • @AmiTavory 没有收到您的评论,这是什么意思?
  • binded 成员函数的第一个参数是它将调用的实例,即 "impicit this"
  • @Revolver_Ocelot 好的,第二个参数没有参数,但 jt 接受呢?
  • @AmiTavory 我明白了,但是第二个参数呢?我是说dt?

标签: c++ c++11 stdbind


【解决方案1】:
std::bind(&Aircraft::fire, _1)

1) 有两个参数传递给std::bind。第一个参数是&amp;Aircraft::fire,一个指向成员函数Aircraft::fire的指针。第二个参数是std::placeholders::_1,由于在某处存在using namespace std::placeholders,因此通过非限定查找找到。

fn(static_cast<GameObject &>(node), dt)

2) 参数 static_cast&lt;GameObject &amp;&gt;(node) 替换了 _1 占位符。 Aircraft::fire 有一个参数,即隐式this,因此static_cast&lt;GameObject &amp;&gt;(node) 作为隐式this 参数提供给Aircraft::fire。参数dt 将替换_2 占位符,但由于没有_2,它被忽略了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    相关资源
    最近更新 更多