views:

75

answers:

1

I don't understand why in the following code, I am allowed to create the function print_private_template while the compiler complains about print_private_class:

#include <cstdio>

class A
{
    private:
        template <unsigned T>
        struct B
        {

        };

        struct C
        {

        };

    public:
        template <unsigned T>
        B<T> getAb()
        { 
            return B<T>();
        }

        C getAc()
        { 
            return C();
        }
};

template<unsigned T>
void print_private_template(const A::B<T> &ab)
{
    printf("%d\n", T);
}

void print_private_class(const A::C &ac)
{
    printf("something\n");
}

int main(int, char**)
{
    A a;

    print_private_template(a.getAb<42>());

    print_private_class(a.getAc());

    return 0;
}

Is this an expected behaviour? a compiler bug/extension?

Just to be clear, my goal is to make the compiler error on both the usage of print_private_template and print_private_class.

+2  A: 

Comeau does give an error (when you comment out the print_private_class function and its call in strict C++03 mode.

ComeauTest.c(31): error: class template "A::B" (declared at line 7) is inaccessible void print_private_template(const A::B &ab) ^ detected during instantiation of "print_private_template" based on template argument <42U> at line 45

G++ 4.5 on Windows does not report any error with -std=c++ -Wall -pedantic though.

Your class A::C and class template A::B<T> both have the same visibility as any other normal members. Hence, both print_private_class and print_private_template require a diagnostic.

11.8 Nested classes [class.access.nest]

1 A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class; the usual access rules (Clause 11) shall be obeyed.

dirkgently
I take it I found a compiler bug in GCC then?
LiraNuna
IIRC, GCC 4.5 (the one I am using) is an experimental build. There are bound to be some issues with the implementation quality. But, yes of course, you can go ahead and file this.
dirkgently
I am using GCC 4.4.3, so I doubt the issue is coming from your unstable build.
LiraNuna
Wow, this seems like a REALLY old bug! I can reproduce this from GCC 3.4 and beyond! GCC 3.3 errors as it should, though.
LiraNuna
Hm. Inner classes have been a pain to work with with most compilers till very recently. I see you've already filed a bug (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=45775 for others). Hope this gets fixed soon!
dirkgently