#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;
}
该代码旨在从父类的模板成员函数访问子类的成员。我想这样做是因为模板成员函数不能是虚拟的。我得到的错误是:“'Child' 是一个不完整的类型”。我该如何进行这项工作?
最佳答案
可以将f
的定义和声明分开,将定义移到类Child
的定义之后。例如
class Child;
class Parent {
public:
virtual ~Parent() = default; // must be polymorphic type
template <class Function, class... Args>
void f(Function&& f, Args&&... args); // the declaration
};
class Child : public Parent {
public:
int n = 0;
};
// the definition
template <class Function, class... Args>
void Parent::f(Function&& f, Args&&... args)
{
Child *c = dynamic_cast<Child*>(this);
if (c != nullptr) // check the result of conversion
cout << c->n;
}
注意
- 基类
Parent
必须是 polymorphic type使用dynamic_cast ;即它必须至少有一个virtual
函数。 - 你最好在使用前检查
dynamic_cast
的结果。
关于c++ - 如何从父模板函数访问子成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41437006/