2017-01-03 80 views
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; 
} 

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

回答

3

你可以分开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; 
} 

注意

  1. 基类Parent必须polymorphic type使用dynamic_cast;即它必须至少具有一个功能。
  2. 您最好在使用前检查dynamic_cast的结果。
相关问题