【发布时间】:2017-01-10 22:57:05
【问题描述】:
我很难理解为什么以下 sn-p 编译。我有一个模板类ptr_to_member<T>,它存储了一个指向T 成员函数的指针。然后我正在创建一个新类my_class,它有一个ptr_to_member<my_class>。鉴于my_class 仍在定义中,我预计后者会导致编译错误。任何帮助表示赞赏。谢谢。
#include <iostream>
// this class simply stores a pointer to a member function of T
template <class T>
struct ptr_to_member {
using ptr_type = void (T::*)();
ptr_type m_ptr;
ptr_to_member()
: m_ptr(&T::f){}
auto get_ptr() const {
return m_ptr;
}
};
// my_class has a ptr_to_member<my_class>
class my_class {
ptr_to_member<my_class> m_ptr_to_member; // why does this compile?
public:
void g() {
auto ptr = m_ptr_to_member.get_ptr();
(this->*ptr)();
}
void f() {
std::cout << "f" << std::endl;
}
};
int main() {
my_class x;
x.g();
}
【问题讨论】:
标签: c++ pointer-to-member