简体   繁体   English

访问基模板类的每个成员

[英]Access every member of base template class

When you use template inheritence, you have to explicitly specify what members of base template class you intend to use:当您使用模板继承时,您必须明确指定您打算使用的基模板类的成员:

template <typename T>
class base 
{
protected:
    int x;
};

template <typename T>
class derived : public base<T> 
{
public:
    int f() { return x; }
protected:
    using base<T>::x;
};

What if base template has a lot of members?如果基本模板有很多成员怎么办? Can I avoid writing using declaration for each member and specify that I want every member of base template?我可以避免为每个成员编写using声明并指定我想要基本模板的每个成员吗?

不。在语言中没有这样的机制。

For that reason, i usually introduce a member named inherited .出于这个原因,我通常会引入一个名为inherited的成员。

eg例如

using inherited = base<T>;

Then to access the members of the base class, the code would look like:然后访问基类的成员,代码如下所示:

int f() { return inherited::x; }

This approach has the advantage, that you can easily differentiate which member you are referring to (if required, using this only for own members).这种方法的优点是,你可以很容易区分你是指哪些成员(如果需要的话,使用this只为自己的成员)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM