15

コード:

// 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はそれらを見つけられないのですか?

4

1 に答える 1

26

thisポインタを介して、クラステンプレートの基本クラスメンバー関数を明示的に呼び出す必要があります。

// ...

template<typename T>
struct ptr_stack_tp<T*> : public stack<T*>
{
    ~ptr_stack_tp()
    {
        while (!this->empty()) {
        //      ^^^^^^
            operator delete(this->top());
            //              ^^^^^^
            this->pop();
        //  ^^^^^^
        }
    }
};

// ...

これは、2フェーズの名前ルックアップがテンプレートに対して機能する方法によるものです。間接参照がないthis->場合、コンパイラは非修飾名をグローバル関数の名前として解決しようとします。empty()、、、top()およびという名前のグローバル関数pop()が存在しないため、コンパイラはエラーを発行します。

を使用している場合this->、コンパイラは、テンプレートが実際にインスタンス化される瞬間まで名前の検索を遅らせます。その時点で、基本クラスのメンバーへの関数呼び出しは正しく解決されます。

于 2013-03-19T16:25:50.480 に答える