Ben Whale
Ben Whale

Reputation: 493

Member access of template specialisation in unspecialised template

The following code fails to compile (using clang):

template<int N>
class Foo {
    public:
        Foo() : value(N) { }

        void getValue(Foo<1>& foo)
        {
            value = foo.value;
        }

    protected:
        int value;
};

int main(int argc, const char * argv[])
{
    Foo<1> fooOne = Foo<1>();

    Foo<2> fooTwo = Foo<2>();

    fooTwo.getValue(fooOne);

    return 0;
}

The error is main.cpp:21:15: error: 'value' is a protected member of 'Foo<1>'. Which is all well and good.

My question is is there a way to get this to work using friend? For example the following code produces the same error, but I hoped that it would have worked.

template<int N>
class Foo {
    public:
        Foo() : value(N) { }

        friend class Foo<1>;

        void getValue(Foo<1>& foo)
        {
            value = foo.value;
        }

    protected:
        int value;
};

I can of course be terribly horrible and use the tricks in Accessing protected member of template parameter or http://www.gotw.ca/gotw/076.htm. But I'd rather not resort to hackery of that level for something that I'm probably just being dense about.

Upvotes: 1

Views: 45

Answers (1)

Barry
Barry

Reputation: 303387

You're friend-ing the wrong way. It's Foo<N> that needs to be a friend of Foo<1>, since it needs to access Foo<1>'s internals; you are making Foo<1> a friend of Foo<N>. For simplicity, you could just friend all of them:

template <int N>
class Foo {
    // mass inter-Foo friendship
    template <int > friend class Foo;

    // rest as you had before
};

Upvotes: 2

Related Questions