Re: Template cannot access its own protected members? huh?
On 4/10/2014 7:21 PM, cpisztest@gmail.com wrote:
[..]
I guess I am misinterpreting the word "access." In my mind, looking
at
the code above, no one is accessing anything. I was under the impression
that "access" in the error message above had to mean: "Somewhere in the
implementation of the code that comes from expanding R2<Test>, someone
is calling a private or protected method or looking at private or
protected data." In your example, noone calls anything and noone looks
at any data at all. It is as if simply declaring a friend _is access_.
Right?
Well, yes, according to the Standard, [class.friend]/9:
<<A name nominated by a friend declaration shall be accessible in the
scope of the class containing the friend
declaration.>>
So, how do I allow the template class access to the protected and
private methods and members of it's T arguments properly?
There are two ways. One, the template could grant the template argument
type friendship so that the type can access the protected members of the
template for whatever they are needed:
#include <iostream>
class Base
{
public:
virtual void foo() = 0;
};
template<class T> class NeedsAccess : public Base
{
friend T;
protected:
void foo() { T::doStuff(); } // protected overrider
};
class Arg
{
friend void NeedsAccess<Arg>::foo();
static void doStuff() { std::cout << "stuff\n"; } // private
};
int main()
{
NeedsAccess<Arg> na;
Base *pb = &na;
pb->foo();
}
If that solution doesn't look good, since 'Arg' doesn't need access to
everything except a couple of functions, you could make them both
befriend some intermediary, and let that intermediary conduct all the
necessary communication between the objects.
There are examples of that on the Web, I am sure.
V
--
I do not respond to top-posted replies, please don't ask