I'm having a hard time understanding why the following snippet compiles. I have a template class ptr_to_member<T>
which stores a pointer to a member function of T
. I am then creating a new class my_class
which has a ptr_to_member<my_class>
. I expected the latter to cause a compilation error given that my_class
is still being defined. Any help is appreciated. Thank you.
#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();
}