C++类模板继承难题

发布于 2024-12-13 03:06:43 字数 351 浏览 1 评论 0原文

这段代码有什么问题? gcc 4.6.1 抱怨 baz() 中的“'foo' 未在此范围内声明”。如果我转换代码,使其中一个模板只是一个常规类,那么问题就会消失。

struct Foo {
    char foo;
};

template<int N>
struct Bar : public Foo
{
    Bar() { foo; }
};

template<int N>
struct Baz : public Bar<N>
{
    void baz() { foo; }
};

int main() {
    Baz<10> f;
    return 0;
}

What's wrong with this code? gcc 4.6.1 is complaining "‘foo’ was not declared in this scope" in baz(). If I transform the code so that one of the templates is just a regular class, the problem goes away.

struct Foo {
    char foo;
};

template<int N>
struct Bar : public Foo
{
    Bar() { foo; }
};

template<int N>
struct Baz : public Bar<N>
{
    void baz() { foo; }
};

int main() {
    Baz<10> f;
    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

四叶草在未来唯美盛开 2024-12-20 03:06:43

根据规范,我不知道出了什么问题,但是您可以使用以下命令来编译代码:

void baz() { Bar<N>::foo; }

What is wrong, according to the specifications, I don't know, but you may make your code to compile by using:

void baz() { Bar<N>::foo; }
醉殇 2024-12-20 03:06:43

foo 是一个从属名称;也就是说,它取决于模板参数,因此在实例化模板之前,编译器不知道它是什么。您必须明确它是一个类成员,可以是 Bar::foothis->foo

(您可能还想用它做一些事情;简单地将它用作表达式的忽略值根本不会做任何事情)。

foo is a dependent name; that is, it depends on the template parameter, so until the template is instantiated the compiler doesn't know what it is. You have to make it clear that it is a class member, either Bar<N>::foo or this->foo.

(You probably also want to do something with it; simply using it as the ignored value of an expression doesn't do anything at all).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文