C++类模板继承难题
这段代码有什么问题? 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据规范,我不知道出了什么问题,但是您可以使用以下命令来编译代码:
What is wrong, according to the specifications, I don't know, but you may make your code to compile by using:
foo
是一个从属名称;也就是说,它取决于模板参数,因此在实例化模板之前,编译器不知道它是什么。您必须明确它是一个类成员,可以是Bar::foo
或this->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, eitherBar<N>::foo
orthis->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).