1

I want to use as arguments pointers to functions in constructor of my class JQCollider. But I am getting this error when I am constructing object.

Before I have got error "non-standard syntax; use '&' to create a pointer to member " so I added '&' to every pointer to member argument.But when I am compiling I am getting now this error.

class JQCollider
{
public:

    JQCollider()
    {

    }
    JQCollider(FloatRect getBounds(), Vector2f getPos(),void setPos(Vector2f pos))
    {
    getObjPos = getPos;
    getObjBounds = getBounds;
    setObjPos = setPos;
    }

private:

    Vector2f(*getObjPos)();
    FloatRect(*getObjBounds)();
    void(*setObjPos)(Vector2f);

}

class JQTextBox
{
public:
    JQTextBox()
    {
    }

    void Initialize()
    {
    collision = JQCollider(&textBoxSprite.getGlobalBounds, &textBoxSprite.getPosition, &textBoxSprite.setPosition);
    }
private:
    JQCollider collision;
    Sprite textBoxSprite;
}


  • 1
    https://stackoverflow.com/questions/400257/how-can-i-pass-a-class-member-function-as-a-callback – VLL Apr 12 '19 at 12:42
  • @Ville-Valtteri One of the anwsers look like solution to this problem, but I need to make JQCollider template or special constructor for every class that functions I want to use? – JQ Technologies Apr 12 '19 at 13:08

1 Answers1

1

You can't create a function pointer to a member function of a specific instance. Instead, use std::function and std::bind:

#include <functional>

class JQCollider
{
public:
    JQCollider()
    {}

    JQCollider(std::function<FloatRect>()> getBounds, std::function<Vector2f>()> getPos,
        std::function<void(Vector2f)> setPos)
    {
        getObjPos = getPos;
        getObjBounds = getBounds;
        setObjPos = setPos;
    }

private:
    std::function<Vector2f>()> getObjPos;
    std::function<FloatRect>()> getObjBounds;
    std::function<void(Vector2f)> setObjPos;
}

class JQTextBox
{
public:
    JQTextBox()
    {}

    void Initialize()
    {
        collision = JQCollider(std::bind(&Sprite::getGlobalBounds, textBoxSprite),
            std::bind(&Sprite::getPosition, textBoxSprite),
            std::bind(&Sprite::setPosition, textBoxSprite, std::placeholders::_1));
    }

private:
    JQCollider collision;
    Sprite textBoxSprite;
}
VLL
  • 9,634
  • 1
  • 29
  • 54