c ++模板似乎打破了访问说明符

tjm*_*tjm 3 c++ templates

以下代码由于显而易见的原因而无法编译,即Foo正在尝试访问Bar的私有成员.但是,如果您取消注释/注释标记的行,使Foo成为模板,它会编译并输出42.我在这里缺少什么?为什么这样做?在我看来它不应该.

谢谢你的帮助.

#include <iostream>

class Bar {
    private:
    static const int x = 42;
};

//template <int>   // uncomment me
struct Foo {
    static const int i = Bar::x;
};

int main(int argc, char* argv[]) {

    std::cout << Foo::i    << std::endl;   // comment me
    //std::cout << Foo<0>::i << std::endl;   // uncomment me
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*lis 5

如果您看到此行为,则是编译器错误.

Comeau Online和Visual C++ 2010都拒绝将代码视为无效,因为Bar::x无法访问.g ++ 4.1.2错误地接受了无效代码(有人需要使用更高版本进行测试以查看它是否已被修复;这是我在这台笔记本电脑上唯一的版本).