2017-01-03 7 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. 基底クラスParentdynamic_castを使用するpolymorphic typeでなければならないことに注意してください。すなわち、少なくとも1つのvirtual機能を持たなければならない。
  2. dynamic_castの結果を確認してから使用することをお勧めします。
関連する問題