C ++模板隐藏父成员 [英] C++ templates hides parent members

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

问题描述

通常,当 A 继承自 B 时, A 会自动显示给 B 的函数,例如

Usually, when A is inheriting from B, all the members of A are automatically visible to B's functions, for example

class A {
protected:
    int a;
};

class B : public A {
    int getA() {return a;}
    //no need to use A::a, it is automatically visible
};

但是当我继承模板时,这个代码变成非法c> gcc )

However when I'm inheriting with templates, this code becomes illegal (at least in gcc)

template<typename T>
class A {
protected:
    int a;
};

template<typename T>
class B : public A<T> {
    int getA() {return a;}
};

templt.cpp: In member function `int B<T>::getA()':
templt.cpp:9: error: `a' undeclared (first use this function)
templt.cpp:9: error: (Each undeclared identifier is reported only once for each
function it appears in.)

我必须做

class B : public A<T> {
    using B::a;
    int getA() {return a;}
};

class B : public A<T> {
    using A<T>::a;
    int getA() {return a;}
};

class B : public A<T> {
    int getA() {return B::a;}
};

等。如下变量 a B 的另一个变量隐藏,在以下情况下:

etc. As if the variable a is hidden by another variable of B, in the following case:

class HiddenByOverload {void hidden(){}}
class HidesByOverload : public HiddenByOverload {
    void hidden(int i) {} //different signature, now `hidden` is hidden
    void usehidden() {
        HiddenByOverload::hidden(); // I must expose it explicitly
    }
}

?有没有其他方法来阻止C ++隐藏父模板类的变量?

Why is it so? Are there any other ways to prevent C++ from hiding the parent template class' variables?

编辑:感谢大家的迷人的讨论。我必须承认我没有遵循引用C ++标准中的段落的论点。我很难在没有阅读实际来源的情况下去关注它。

thanks for everyone for the fascinating discussion. I must admit I didn't follow the argument which quoted paragraphs from the C++ standard. It's hard for me to follow it without reading the actual source.

我可以做的最好的事情来总结讨论,引用一条短线从禅宗的Python :

The best thing I can do to summarize the discussion, is quoting a short line from "The Zen of Python":


如果实现很难,
解释,它可能是个坏主意。

If the implementation is hard to explain, it's (probably) a bad idea.


推荐答案

您也可以执行

class B : public A<T> {
    int getA() {return this->a;}
};

问题是成员在基础中,这取决于模板参数。正常的非限定查找在定义点执行,而不是在实例化点执行,因此它不搜索依赖的基础。

The problem is that the member is in a base, which depends on a template parameter. Normal unqualified lookup is performed at the point of definition, not at the point of instantiation, and therefore it doesn't search dependent bases.

这篇关于C ++模板隐藏父成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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