#include <iostream>
#include <functional>
using namespace std;
class Child;
class Parent {
public:
template <class Function, class... Args>
void f(Function&& f, Args&&... args)
{
Child *c = dynamic_cast<Child*>(this);
cout << c->n;
}
};
class Child : public Parent {
public:
int n = 0;
};
int main()
{
Parent *p = new Child();
cout << "abc";
return 0;
}
The code intends to access child class's member from parent's template member function. I'd like to do this because the template member function cannot be virtual. The error I got is: "'Child' is an incomplete type". How do I make this work?
You can separate
f
's definition and declaration, and move the definition after the definition of classChild
. e.g.Note that
Parent
must be polymorphic type to use dynamic_cast; i.e. it must have at least onevirtual
function.dynamic_cast
before using it.