访问模板参数的受保护成员 [英] Accessing protected member of template parameter

查看:228
本文介绍了访问模板参数的受保护成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);

我的问题是访问受保护的方法。我尝试把朋友类T 放入Bar,但似乎不允许在c ++(编辑:并不会解决我的问题反正,所以它似乎) 。我尝试让Bar继承自T( template< typename T> class Bar:public T (可以使用私人继承,但是Bar的公共接口不是非常重要,因为类本身是内部的)),但是不允许访问 foo()。那么如何访问 foo()方法?

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?

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

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).

推荐答案

在地狱黑客。您可以滥用这样的事实,您可以从派生类中形成指向受保护的基础成员的指针。

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);
}

这篇关于访问模板参数的受保护成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆