对std::函数对象的调用不匹配,该对象是指向成员函数的指针



我希望一个类持有指向不同类的成员函数的函数指针。

但是,当我尝试使用函数指针调用该成员函数时,会出现以下错误:

No match for call to '(const std::function<bool(PropertyCache&)>) ()'

我不使用原始函数指针,而是使用std::function对象,因为如果你想指向成员函数(它们需要对我调用其成员函数的类的实例的引用(,就可以这样做。

所以我的第一堂课是:

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

它也是一个抽象基类的子类,但我想这对现在来说并不重要。基本上,Condition持有指向Cache类的getter的函数指针,然后获取最新值并将其与给定值进行比较。

Cache类如下所示:

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

下面是我如何在我的主要功能中使用它:

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;

你说"函数"对象m_getter需要引用一个Cache对象作为参数。

虽然您需要将Cache对象传递给您调用的函数(setIsLampOngetIsLampOn(是正确的,但您在调用中将该对象设置为std::bind

对于您当前的m_getter,您需要将其称为m_getter(SomeCacheObject)

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

std::function<bool()> m_getter;

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

最新更新