繁体   English   中英

对 std::function object 的调用不匹配,它是指向成员 function 的指针

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

我想要一个 class 来保存一个 function 指针,该指针指向另一个 ZA2F2ED4F8EBC2CBBDZC2A 的成员 function。

但是当我尝试使用 function 指针调用该成员 function 时得到的是错误:

调用 '(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).

所以我的第一个 class 如下:

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;
};

它也是抽象基础 class 的子类,但我想这目前并不重要。 基本上,一个 Condition 将 function 指针指向缓存 class 的 getter,然后获取最新值并将其与给定值进行比较。

缓存 class 如下所示:

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

private:
    bool m_isLampOn;
};

然后这是我在我的主要 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));

所以我想使用的一个条件基本上是检查灯的值是否为真。

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

您说“函数” object m_getter需要引用Cache object 作为参数。

虽然您需要将Cache object 传递给您调用的 function 是正确的( setIsLampOngetIsLampOn ),但您在调用std::bind时将此 ZA8CFDE6331BD59EB2AC96F8911C4B6.66Z 设置为:

使用当前的m_getter ,您需要将其称为m_getter(SomeCacheObject)

你不应该让m_getter需要一个参数:

std::function<bool()> m_getter;

现在您可以将其称为m_getter()并且将使用您随std::bind提供的Cache object。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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