C ++中的继承和模板 - 为什么方法不可见? [英] Inheritance and templates in C++ - why are methods invisible?

查看:122
本文介绍了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?

推荐答案

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

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天全站免登陆