【发布时间】:2010-04-08 17:51:36
【问题描述】:
我正在使用一个定义接口的库:
template<class desttype>
void connect(desttype* pclass, void (desttype::*pmemfun)());
我有一个小的层次结构
class base {
void foo();
};
class derived: public base { ... };
在derived的一个成员函数中,我想调用
connect(this, &derived::foo);
但貌似&derived::foo其实是base的成员函数指针; gcc 吐出来
error: no matching function for call to ‘connect(derived* const&, void (base::* const&)())’
我可以通过将this 显式转换为base * 来解决此问题;但是为什么编译器不能将调用与desttype = base 匹配(因为derived * 可以隐式转换为base *)?
另外,为什么是 &derived::foo 不是derived 的成员函数指针?
【问题讨论】:
-
是否有充分的理由使用指向成员函数的指针,而不是仅仅在基中声明一个(纯?)虚函数,并在需要时调用它?
-
@Jerry Coffin:有的时候-有。调用纯虚函数的唯一方法是通过该函数的硬编码名称。当硬编码特定函数不可接受时,使用指向成员的指针。这一定是其中一种情况。
标签: c++ casting member-function-pointers