2017-01-03 79 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的結果。
相關問題