简体   繁体   English

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

[英]c++ template seems to break access specifiers

The following code doesn't compile for obvious reasons, namely that Foo is trying to access a private member of Bar. 以下代码由于显而易见的原因而无法编译,即Foo正在尝试访问Bar的私有成员。 However if you uncomment/comment the lines marked, making Foo a template, it does compile and outputs 42. What am I missing here? 但是,如果您取消注释/注释标记的行,使Foo成为模板,它会编译并输出42.我在这里缺少什么? Why does this work? 为什么这样做? Seems to me it shouldn't. 在我看来它不应该。

Thanks for your help. 谢谢你的帮助。

#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
}

If you are seeing this behavior, it is a compiler bug. 如果您看到此行为,则是编译器错误。

Both Comeau Online and Visual C++ 2010 reject the code as invalid because Bar::x is inaccessible. Comeau Online和Visual C ++ 2010都拒绝将代码视为无效,因为Bar::x无法访问。 g++ 4.1.2 incorrectly accepts the invalid code (someone would need to test with a later version to see if it's been fixed; that's the only version I have on this laptop). g ++ 4.1.2错误地接受了无效代码(有人需要使用更高版本进行测试以查看它是否已被修复;这是我在这台笔记本电脑上唯一的版本)。

This seems like GCC bug 40843 . 这看起来像GCC bug 40843 It is listed as UNCONFIRMED, but I can reproduce it on g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3 as well. 它被列为UNCONFIRMED,但我也可以在g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3上重现它。

VisualStudio 2010说“错误C2248:'Bar :: x'[...]由于平台没有规定,我已经评估了几乎在Windows VC9上的假设是假的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM