我知道SGI STL和我一样年纪,但我仍想弄明白。
在stl_stack.h中,有一些代码如下:
template <class T, class Sequence = Deque<T> >
class Stack {
friend bool operator== __STL_NULL_TMPL_ARGS (const Stack&, const Stack&);
friend bool operator< __STL_NULL_TMPL_ARGS (const Stack&, const Stack&);
protected:
Sequence c;
};
template <class T, class Sequence>
bool operator== (const Stack<T, Sequence>& x, const Stack<T, Sequence>& y){
return x.c == y.c;
}
template <class T, class Sequence>
bool operator< (const Stack<T, Sequence>& x, const Stack<T, Sequence>& y){
return x.c < y.c;
}
在stl_config.h中,__STL_NULL_TMPL_ARGS
的定义如下:
# ifdef __STL_CLASS_PARTIAL_SPECIALIZATION
# define __STL_TEMPLATE_NULL template<>
# else
# define __STL_TEMPLATE_NULL
# endif
但是当我尝试用G ++ 4.9.2编译它时,编译器说:
In file included from stack.cpp:1:0:
stack.h:13:22: error: declaration of ‘operator==’ as non-function
friend bool operator== __STL_NULL_TMPL_ARGS (const Stack&, const Stack&);
^
stack.h:13:22: error: expected ‘;’ at end of member declaration
In file included from iterator.h:3:0,
from deque.h:6,
from stack.h:5,
from stack.cpp:1:
stl_config.h:111:31: error: expected unqualified-id before ‘<’ token
# define __STL_NULL_TMPL_ARGS <>
^
stack.h:13:25: note: in expansion of macro ‘__STL_NULL_TMPL_ARGS’
friend bool operator== __STL_NULL_TMPL_ARGS (const Stack&, const Stack&);
我不知道为什么完全相同的代码无法在我的计算机上编译,这个代码现在是非法代码还是什么?
非常感谢!!!
答案 0 :(得分:1)
stl_stack.h
有一个错误,必须在当代编译器的雷达之下。在operator== <>
被声明为模板之前提及operator==
是违法的。
要解决此问题,请在operator==
的定义之前声明stack
。但如果你在那时宣布它,你也可以定义它。宣言将要求stack
:
template <class T, class Sequence>
class stack; // Forward declare for sake of operator== declaration.
template <class T, class Sequence>
bool operator==(const stack<T, Sequence>& x, const stack<T, Sequence>& y) {
return x.c == y.c;
}
#ifndef __STL_LIMITED_DEFAULT_TEMPLATES
template <class T, class Sequence = deque<T> >
#else
…
(当然,将operator==
定义添加到顶部后,您将从底部删除它。)