访问模板参数的受保护成员

Gri*_*zly 0 c++ templates visibility

我有一个模板类,我需要访问模板参数的受保护成员函数,如下所示:

class Foo
{
protected:
    void foo() {}
};

template<typename T>
class Bar
{
public:
    static void bar(T& self){self.foo();}
};
...
Foo f;
Bar<Foo>::bar(f);
Run Code Online (Sandbox Code Playgroud)

我的问题是访问受保护的方法.我尝试将一个friend class T进入Bar,但在c ++中似乎不允许这样做(编辑:并且无论如何都不会解决我的问题,所以它似乎).我试过让Bar继承自T(template<typename T> class Bar: public T(本来可以使用私有继承,但Bar的公共接口并不是非常重要,因为类本身只是内部的)),但这不允许访问foo()任何一个.那么我该如何访问该foo()方法?

编辑: Foo不应该知道Bar<Foo>,因为有很多Bar类.然而,我可以对Foo进行其他更改(当然不改变公共接口).

CB *_*ley 5

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.

class Foo
{
protected:
    void foo() {}
};

// Helper template to bypass protected access control
// for a member function called foo, taking no parameters
// and returning void.
template<typename T>
struct Unprotect : public T
{
    typedef void (T::*FooPtr)();
    static FooPtr GetFooPtr()
    {
        return &Unprotect::foo;
    }
};

template<typename T>
class Bar
{
public:
    static void bar(T& self){(self.*Unprotect<Foo>::GetFooPtr())();}
};

int main()
{
    Foo f;
    Bar<Foo>::bar(f);
}
Run Code Online (Sandbox Code Playgroud)