C ++使用std :: function和std :: bind不调用函数委托成员函数

时间:2014-09-18 01:36:13

标签: c++ c++11 delegates member-function-pointers

令我感到困惑。下面我们有三个类,Paddle类和两个调用Paddle对象成员的包装类。

Paddle对象不与代理一起工作,但在从包装类调用时可以正常工作。所有功能都具有相同的签名和重载。

编译器不会抛出任何错误,代码运行正常但具有上述意外行为。

为什么会这样?

// sf::Transformable has 2 overloaded member functions:
//   void setPosition(float x, float y);
//   void setPosition(const Vector2f& position);

class Paddle : public sf::Drawable, public sf::Transformable {}

Paddle paddle{};

// wrap the calls in another class with the same overload signatures as paddle
// used to show delegate working with overloads
class A 
{
public:
    void setPosition(sf::Vector2f& v) {
        paddle.setPosition(v);
    }
    void setPosition(float x, float y) {
        paddle.setPosition(x, y);
    }
};

// inherit members from A
// used to show delegate working with inherited overloads
class B : public A {};

// delegate typedef
typedef std::function<void(float,float)> TranslateDelegate;

// create wrapper classes
A a{};
B b{};

// create 3 delegates
TranslateDelegate pda = std::bind(static_cast<void(A::*)(float, float)>(&A::setPosition), a, std::placeholders::_1, std::placeholders::_2);
TranslateDelegate pdb = std::bind(static_cast<void(B::*)(float, float)>(&B::setPosition), b, std::placeholders::_1, std::placeholders::_2);
TranslateDelegate pdp = std::bind(static_cast<void(Paddle::*)(float, float)>(&Paddle::setPosition), paddle, std::placeholders::_1, std::placeholders::_2);

pda(300.f, 900.f); // sets paddle position correctly
pdb(300.f, 900.f); // sets paddle position correctly
pdp(300.f, 900.f); // DOES NOTHING!!

1 个答案:

答案 0 :(得分:1)

想出来。对于paddle来说,我需要将地址传递给std :: bind,这与a和b:

不同
TranslateDelegate pdp = std::bind(static_cast<void(Paddle::*)(float, float)>(&Paddle::setPosition), &paddle, std::placeholders::_1, std::placeholders::_2);

我假设这是因为A和B中的函数在上下文中工作或被称为静态类函数。