tags:

views:

146

answers:

3

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
}
+5  A: 

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).

James McNellis
oh ok, thanks. I'm using gcc 4.4.3, should have mentioned that in the post
tjm
gcc 4.5.0 barks on the code as well. If I remember correctly clang doesn't do access checking yet.
pmr
Yeah, [send this to the gcc folks](http://gcc.gnu.org/bugs/).
Mike DeSimone
A: 

VisualStudio 2010 said "error C2248: 'Bar::x' [...] As the plateform was not speciifed, I have assessed that the assumption is false almost on Windows VC9.

tojas
-1. That's definitely not helpful.
Alexander Gessler
+3  A: 

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.

Thomas
Thanks, this is helpful. Lets me know that it's known and stops me filing an unnecessary new bug report should I want to report my experience of it. Unfortunately I can't upvote because I'm not a registered user, but I would if I could and will when I am!
tjm
@Thomas: Good catch; I didn't find that one when I searched. +1
James McNellis