c++ - 对依赖基类成员的非限定访问导致 "A declaration of [x] must be available"

标签 c++ templates stack

代码:

// 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-> 间接,编译器会尝试将 unqualified 名称解析为全局函数的名称。由于不存在名为 empty()top()pop() 的全局函数,因此编译器会报错。

当您使用 this-> 时,编译器会将名称查找延迟到模板实际实例化的那一刻:此时,对基类成员的函数调用将是正确解决。

关于c++ - 对依赖基类成员的非限定访问导致 "A declaration of [x] must be available",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15504944/

相关文章:

c++ - 如何隐式专门化转换?

c++ - 如何在 C++ 中编译位于不同文件中的模板?

c - Linux 核心中的通用堆栈实现

c++ - QGraphicsView/Scene - 项目绘制距离鼠标点击 2 倍

c# - 包含 atlbase.h header 时应用程序崩溃

c++ - 具有未使用模板参数的函数模板

javascript - Photoshop 脚本。打开和保存重叠图像堆栈

c# - 可观察的堆栈和队列

c++ - 参数接收的对象上的函数指针

c++ - 函数模板和迭代器