C ++ template base class hiding members?

Both clang ++ and g ++ complain about the following code:

#include <iostream>

template<unsigned N>
class A {
public:
    int k;
    void printk() {std::cout << k << std::endl;}
    A() : k(0) {}
};

template<unsigned N>
class B : public A<N> {
public:
    B() {
        this -> k ++; // OK
        A<N> :: k ++; // OK
        //      k ++; // error: ‘k’ was not declared in this scope
    }
};

int main () {
    B<1>().printk(); // prints "2"
}

If I do not declare Bas a template, I can use kwithout additional qualifications:

#include <iostream>

template<unsigned N>
class A {
public:
    int k;
    void printk() {std::cout << k << std::endl;}
    A() : k(N) {}
};

class B : public A<0> {
public:
    B() {
        this -> k ++; // OK
        A<0> :: k ++; // OK
                k ++; // OK
    }
};

int main () {
    B().printk(); // prints "3"
}

Or, if I do not declare A as a template:

#include <iostream>

class A {
public:
    int k;
    void printk() {std::cout << k << std::endl;}
    A() : k(0) {}
};

template<unsigned N>
class B : public A {
public:
    B() {
        this -> k += N; // OK
        A ::    k += N; // OK
                k += N; // OK
    }
};

int main () {
    B<1>().printk(); // prints "3"
}

Why? (I assume this is not a mistake, since both compilers behave the same.) Should it be like that?

+4
source share

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


All Articles