【发布时间】:2019-11-11 14:20:05
【问题描述】:
我想要一个类保存一个指向不同类的成员函数的函数指针。
但是当我尝试使用函数指针调用该成员函数时,得到的是错误:
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&)>你说这个函数需要一个Cache&。你为什么不把Cache传递给它? -
这也是,我很确定,不是如何将实例绑定到成员函数,因为隐式实例参数是一个指针(即它是
this)。 编辑:根据我的欺骗建议,我收回了它:"std::bind()足够聪明,可以使用任何看起来像指针的东西,任何可转换为适当类型引用的东西(比如std::reference_wrapper<Foo>),或者当第一个参数是指向成员的指针时,将对象的 [副本] 作为对象。"
标签: c++ function-pointers std-function member-functions