C ++模板基类隐藏成员?

时间:2014-04-22 10:13:38

标签: c++ templates inheritance

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,因为两个编译器的行为都相同。)它必须是那样的吗?

0 个答案:

没有答案