4

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 B as template, I can use k without further qualification:

#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 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 is that? (I assume it is not a bug, as both compilers behave the same.) Does it have to be like that?

not-a-user
  • 4,088
  • 3
  • 21
  • 37
  • 1
    Yes, this is standard-compliant behavior. – Constructor Apr 22 '14 at 10:15
  • 6
    it's in the C++ FAQ. lemme giggle it... wait... ok, found, ["Why am I getting errors when my template-derived-class uses a member it inherits from its template-base-class?"](http://www.parashift.com/c++-faq/nondependent-name-lookup-members.html). **it's often a good idea to check the FAQ before asking**. – Cheers and hth. - Alf Apr 22 '14 at 10:18

0 Answers0