1
#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;
}
该代码旨在从父级的模板成员函数访问子类的成员。我想这样做是因为模板成员函数不能是虚拟的。我得到的错误是:“'孩子'是一个不完整的类型”。我如何完成这项工作?如何从父母的模板函数访问子成员?