clang ++和g ++都抱怨以下代码:
#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"
}
如果我不将B
声明为模板,我可以使用k
而无需进一步限定:
#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"
}
或者如果我不将A声明为模板:
#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"
}
为什么? (我认为它不是一个bug,因为两个编译器的行为都相同。)它必须是那样的吗?