C++ 中的继承和模板――为什么继承的成员不可见?

2021-12-13 00:00:00 inheritance templates 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();
}

相关文章