简体   繁体   中英

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. However if you uncomment/comment the lines marked, making Foo a template, it does compile and outputs 42. What am I missing here? 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. 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).

This seems like 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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