对依赖基类成员的不限定访问会导致"A declaration of [x] must be available"
Unqualified access to member of dependent base class results in "A declaration of [x] must be available"
代码:
// test3.cpp
#include <stack>
using namespace std;
template<typename T>
struct ptr_stack_tp;
template<typename T>
struct ptr_stack_tp<T*> : public stack<T*>
{
~ptr_stack_tp()
{
while (!empty()) {
operator delete(top());
pop();
}
}
};
int main()
{}
错误消息(gcc 4.7.2(:
test3.cpp: In destructor 'ptr_stack_tp<T*>::~ptr_stack_tp()':
test3.cpp:15:23: error: there are no arguments to 'empty' that depend on a template parameter, so a declaration of 'empty' must be available [-fpermissive]
test3.cpp:15:23: note: (if you use '-fpermissive', G++ will accept your code, but allowing the use of an undeclared name is deprecated)
test3.cpp:16:33: error: there are no arguments to 'top' that depend on a template parameter, so a declaration of 'top' must be available [-fpermissive]
test3.cpp:17:17: error: there are no arguments to 'pop' that depend on a template parameter, so a declaration of 'pop' must be available [-fpermissive]
函数empty()
、top()
和pop()
是std::stack
的函数,那么,为什么gcc找不到它们呢?
您应该通过this
指针显式调用类模板中的基类成员函数。
// ...
template<typename T>
struct ptr_stack_tp<T*> : public stack<T*>
{
~ptr_stack_tp()
{
while (!this->empty()) {
// ^^^^^^
operator delete(this->top());
// ^^^^^^
this->pop();
// ^^^^^^
}
}
};
// ...
这是由于模板的两阶段名称查找工作方式造成的。如果没有this->
间接寻址,编译器将试图将不合格的名称解析为全局函数的名称。由于不存在名为empty()
、top()
和pop()
的全局函数,编译器将发出错误。
当您使用this->
时,编译器会将名称查找延迟到模板实际实例化的那一刻:此时,对基类成员的函数调用将被正确解析。
相关文章:
- Usages of std::move
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- Declaration of IntRect SFML
- 根据标准,究竟什么是"declaration of an object"
- 为什么海湾合作委员会抱怨"declaration of 'foo' shadows a previous call [-Werror=shadow]"
- MinGW64和"conflicting declaration of C function int select(...)"
- 解决方法:"out of line definition of 'graph' does not match any declaration in 'graph'"
- 获取错误:"error: conflicting types for ‘call_celsius’ "和"note: previous implicit declaration of ‘call_ce
- Clang VS VC++: "error: declaration of 'T' shadows template parameter"
- "ISO C++ forbids declaration of 'list' with no type"错误
- "Declaration of xxx outside of class is not definition"错误
- 不断收到" see declaration of 'class "错误
- 对依赖基类成员的不限定访问会导致"A declaration of [x] must be available"
- 检索 libevent 连接信息时'Forward Declaration of Struct'
- G++ "declaration of "运算符<< " as non-function"
- 零MQ的"expected ';' at the end of declaration list"错误
- C++结构和"error: ISO C++ forbids declaration of '...' with no type"
- 使用 MingW64 C++ "declaration of '__RPC__range' with no type"编译 IMAPI2.h 应用程序时出现错误