I have a template class for which I need to access a protected member function of the template parameter, like this:
class Foo
{
protected:
void foo() {}
};
template<typename T>
class Bar
{
public:
static void bar(T& self){self.foo();}
};
...
Foo f;
Bar<Foo>::bar(f);
My problem is getting access to the protected method. I tried putting a friend class T
into Bar, but that doesn't seem to be allowed in c++ (edit: and wouldn't solve my problem anyways, so it seemd). I tried letting Bar inherit from T (template<typename T> class Bar: public T
(could have used private inheritance, but the public interface of Bar is not terribly important, since the class itself is internal only)), but that didn't allow for access of foo()
either. So how do I get access to the foo()
method?
Edit:
Foo
should not need to know Bar<Foo>
, since there are quite a lot Bar
classes. I can however make other changes to Foo (without changing the public interface of course).
You did your friend declaration in the wrong direction. If
Bar
saysFoo
is it's friend, that meansFoo
gets access toBar
's private data. ForBar
to get access toFoo
's private data,Foo
has to sayBar
is its friend.OK, this is a "rot in hell" hack. You can abuse the fact that you can form pointers-to-members pointing to protected base members from a derived class.
If you want to access a protected member a derived class of
this
, you can do it with theusing
keyword:If you need B to access a protected member of A when an object is passed to B, you need to declare B as a friend of A: