2016-07-28 5 views
3

テンプレートの継承を使用しようとすると奇妙なエラーが発生します。 これは私のコードです:テンプレートの継承とベースメンバーの変数

template <class T> class A { 
public: 
    int a {2}; 
    A(){}; 
}; 

template <class T> class B : public A<T> { 
    public: 
    B(): A<T>() {}; 
    void test(){ std::cout << "testing... " << a << std::endl; }; 
}; 

そして、これは誤りです:

error: use of undeclared identifier 'a'; did you mean 'std::uniform_int_distribution<long>::a'? 
    void test(){ std::cout << "testing... " << a << std::endl; } 

そして、それは私がこれらのフラグを使用して何かに影響を与える可能性がある場合:

-Wall -g -std=c++11 

私は本当にしないでくださいテンプレートがない純粋なクラスと同じコードがうまく動作するので、何が間違っているかを知る。

+1

'無効テスト(){のstd :: coutの<< "検査..." << A :: << std :: endl; }; ' – Rerito

答えて

4

I really don't know what is wrong since the same code as pure classes without templating works fine.

基底クラス(クラステンプレートA)は、その型がテンプレート引数を知ることなく決定することができない、非依存基本クラスではないからです。 aは非依存の名前です。非依存の名前は、依存する基本クラスでは検索されません。

コードを修正するには、aという名前を付けることができます。従属名はインスタンス化時にのみ検索することができます。その時点で、正確なベースの特殊化が探されなければなりません。

あなたでし

void test() { std::cout << "testing... " << this->a << std::endl; }; 

または

void test() { std::cout << "testing... " << A<T>::a << std::endl; }; 

または

void test() { 
    using A<T>::a; 
    std::cout << "testing... " << a << std::endl; 
}; 
+0

答えをありがとう。それは今意味があります:) –