C ++中的继承和模板-为什么继承的成员不可见? [英] Inheritance and templates in C++ - why are inherited members invisible?

查看:53
本文介绍了C ++中的继承和模板-为什么继承的成员不可见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一个模板从另一个模板公开继承时,不是应该访问基本的公共方法吗?

When a template publicly inherits from another template, aren't the base public methods supposed to be accessible?

template <int a>
class Test {
public:
    Test() {}
    int MyMethod1() { return a; }
};

template <int b>
class Another : public Test<b>
{
public:
    Another() {}
    void MyMethod2() {
        MyMethod1();
    }
};

int main()
{
    Another<5> a;
    a.MyMethod1();
    a.MyMethod2();
}

好吧,GCC对此一无所知...我一定完全想念一些东西明显(大脑融化)。

Well, GCC craps out on this... I must be missing something totally obvious (brain melt). Help?

推荐答案

这是有关从属名称的规则的一部分。在 Method2 范围内, Method1 不是从属名称。因此,编译器不会在依赖的基类中查找它。

This is part of the rules concerning dependent names. Method1 is not a dependent name in the scope of Method2. So the compiler doesn't look it up in dependent base classes.

有两种方法可以解决此问题:使用 this 或指定基本类型。有关此最近的帖子的详细信息或在 C ++常见问题解答中进行。另请注意,您错过了public关键字和分号。这是代码的固定版本。

There two ways to fix that: Using this or specifying the base type. More details on this very recent post or at the C++ FAQ. Also notice that you missed the public keyword and a semi-colon. Here's a fixed version of your code.


template <int a>
class Test {
public:
    Test() {}
    int MyMethod1() { return a; }
};

template <int b>
class Another : public Test<b>
{
public:
    Another() {}
    void MyMethod2() {
        Test<b>::MyMethod1();
    }
};

int main()
{
    Another<5> a;
    a.MyMethod1();
    a.MyMethod2();
}

这篇关于C ++中的继承和模板-为什么继承的成员不可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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