CRTP与受保护的派生成员 [英] CRTP with Protected Derived Member

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

问题描述

CRTP模式中,如果我们希望将派生类中的实现函数保持为受保护的。我们必须将基类声明为派生类的朋友,或使用这样的(我没有尝试过该方法对链接文章)。是否有其他(简单)方法允许将派生类中的实现函数保持为protected?

In the CRTP pattern, we run into problems if we want to keep the implementation function in the derived class as protected. We must either declare the base class as a friend of the derived class or use something like this (I have not tried the method on the linked article). Is there some other (simple) way that allows keeping the implementation function in the derived class as protected?

编辑:这里是一个简单的代码示例:

Here is a simple code example:

template<class D> 
class C {
public:
    void base_foo()
    {
        static_cast<D*>(this)->foo();
    }
};


class D:  public C<D> {
protected: //ERROR!
    void foo() {
    }   
};

int main() {
    D d;
    d.base_foo();
    return 0;
}

上面的代码给出了错误: :foo()'使用g ++ 4.5.1保护,但是如果 protected public

The above code gives error: ‘void D::foo()’ is protected with g++ 4.5.1 but compiles if protected is replaced by public.

推荐答案

这不是一个问题,在派生类中用一行解决:

It's not a problem at all and is solved with one line in derived class:

friend class Base<派生> ;;

#include <iostream>

template< typename PDerived >
class TBase
{
 public:
  void Foo( void )
  {
   static_cast< PDerived* > ( this )->Bar();
  }
};

class TDerived : public TBase< TDerived >
{
  friend class TBase< TDerived > ;
 protected:
  void Bar( void )
  {
   std::cout << "in Bar" << std::endl;
  }
};

int main( void )
{
 TDerived lD;

 lD.Foo();

 return ( 0 );
}

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

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