2016-09-01 10 views
2

テンプレート派生クラスBのメソッドで、テンプレート基本クラスAで定義されている属性を使用します。
これまでのところ、usingの作品が見つかりました。
Aという単一の属性ごとにusingステートメントを書くのは面倒です。
どうすればusing文がたくさん書くのを避けることができますか?"使用しない"テンプレートベースクラスのアクセス属性

#include <iostream> 

using namespace std; 

template <typename T> 
class A{ 
    public: 
     A(){ 
      a = 10; 
     } 
     //virtual destructor 
     virtual ~A(){ 
      cout << "~A() is called" << endl; 
     } 
    protected: 
     T a; 
} ; 

template <typename T> 
class B : public A<T>{ 
    public: 
     void f(void){ 
      cout << a << endl; 
     } 
     virtual ~B(){ 
      cout << "~B() is called" << endl; 
     } 
    private: 
     using A<T>::a; //how to get rid of this? 
} ; 

int main(void){ 
    B<int> bb; 
    bb.f(); 
} 

答えて

4

テンプレートパラメータに依存するクラスを拡張するため、thisは従属名になります。明示的thisを使用する必要があります。

template <typename T> 
struct B : A<T>{ 
    void f(){ 
     std::cout << this->a << std::endl; 
    } 
}; 

それともあなたも、クラス名を指定することができます。

template <typename T> 
struct B : A<T>{ 
    void f(){ 
     std::cout << A<T>::a << std::endl; 
    } 
}; 

第三ソリューションは、当然のことながら、using文ですが。

+4

* "これを取り除く方法[使用]" *:by ** 'this'^_ ^ – Jarod42

2
// how to get rid of this? 

あなたはusing声明を取り除くために

void f(void){ 
     cout << A<T>::a << endl; 
    } 

または

void f(void){ 
     cout << this->a << endl; 
    } 

を書くことができます。

関連する問題