Template inheritance and base element variable

I get a weird error when trying to use template inheritance. This is my code:

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;   };
};

And this is a mistake:

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

And in case this can affect something, I use these flags:

-Wall -g -std=c++11

I really don't know what is wrong, because the same code as pure classes without templates works fine.

+4
source share
1 answer

I really don't know what is wrong, because the same code as pure classes without templates works fine.

This is due to the fact that the base class (template template A) is not an independent base class; its type cannot be defined without knowledge of the template arguments. And Ais an independent name. Independent names do not appear in dependent base classes.

, 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; 
};
+5

Source: https://habr.com/ru/post/1649425/


All Articles