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?