Name lookup, templates, and accessing members of base classes

本文探讨了在C++中当派生类试图调用基类的未定义模板成员函数时遇到的编译错误,并提供了两种解决方案:显示指定作用域或使用this指针进行调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如下的小程序:

#include <iostream> using namespace std; template <typename T> struct Base { int f(); }; template <typename T> struct Derived : Base<T> { int g() { return f(); }; }; int main() { return 0; }

使用g++4.2,编译结果:

x.cc: In member function `int Derived<T>::g()': x.cc:6: error: there are no arguments to `f' that depend on a template parameter, so a declaration of `f' must be available x.cc:6: error: (if you use `-fpermissive', G++ will accept your code, but allowing the use of an undeclared name is deprecated)

具体原因参考: http://gcc.gnu.org/onlinedocs/gcc/Name-lookup.html

说明:使用g++3.2 以及 CC(5.0)是可以编译过的。

解决方法:

1. using Base<T>::f;

2. f => this->f

推荐使用第二种方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值