简体   繁体   中英

No match for call to std::function object which is pointer to member function

I want a class to hold a function pointer to a member function of a different class.

But what I get when trying to call that member function using the function pointer, is the error:

No match for call to '(const std::function) ()'

I don't use raw function pointers but std::function objects as this is the way to go if you want to point to member functions (they need the reference to the instance of the class which I call the member function of).

So my first class is the following:

class Condition : public ICondition
{
public:

    Condition(std::function<bool(Cache&)> cacheGetMethod, bool value)
    {
        m_getter = cacheGetMethod;
        m_value = value;
    }

    virtual bool check() const
    {
        // this is where I get the error, so the way I call the std::function object is wrong?
        return m_getter() == m_value;
    }

    virtual ~Condition() {}

private:
    std::function<bool(Cache&)> m_getter;
    bool m_value;
};

It is also a subclass of an abstract base class but I guess that this is not important for now. Basically a Condition holds the function pointer to the getter of the Cache class to then get the latest value and compare it to a given value.

The Cache class looks like this:

class Cache
{
public:
    void setIsLampOn(bool isOn);
    bool getIsLampOn() const;

private:
    bool m_isLampOn;
};

And then here is how I use it in my main function:

std::shared_ptr<Cache> cache = std::make_shared<Cache>();

std::vector<ICondition*> conditions;
conditions.push_back(new Condition(std::bind(&Cache::getLamp, cache), true));

So the one Condition that I want to use basically checks wether the value of the lamp is true or not.

With

std::function<bool(Cache&)> m_getter;

you say that the "function" object m_getter needs a reference to a Cache object as argument.

While it's correct that you need to pass a Cache object to the function you call ( setIsLampOn or getIsLampOn ) you set this object in your call to std::bind .

With your current m_getter you need to call it as m_getter(SomeCacheObject) .

You should not have m_getter need an argument:

std::function<bool()> m_getter;

Now you can call it as m_getter() and the Cache object you provided with std::bind will be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM