1+ // file: 1config-null-template-arguments.cpp
2+ // test __STL_NULL_TMPL_ARGS in <stl_config.h>
3+ // ref. C++ Primer 3/e, p.834: bound friend function template
4+ // vc6[x] cb4[x] gcc[o]
5+
6+ // 直接理解为若允许**bound friend template(约束模板友元)**
7+ // 则定义为 <> ,否则为空。
8+ // friend bool ooperator== __STL_NULL_TMPL_ARGS(const stack&,const stack&);
9+ // 展开后变成
10+ // friend bool ooperator== <>(const stack&,const stack&);
11+ // 友元类型取决于类被初始化时的类型,但程序必须在类外为友元提供模板定义。
12+
13+ #include < iostream>
14+ #include < cstddef> // for size_t
15+ using namespace std ;
16+
17+ class alloc {
18+ };
19+
20+ // BufSiz为非类型参数
21+ template <class T , class Alloc =alloc, size_t BufSiz=0 >
22+ class deque {
23+ public:
24+ deque () {
25+ cout << " deque" << " " ;
26+ }
27+ };
28+
29+ // 以㆘宣告如果不出现,GCC也可以通过。如果出现,GCC也可以通过。这㆒点和
30+ // C++ Primer 3/e p.834的说法有出入。书㆖说㆒定要有这些前置宣告。
31+ template <class T , class Sequence >
32+ class stack ;
33+
34+ template <class T , class Sequence >
35+ bool operator ==(const stack<T, Sequence> &x,
36+ const stack<T, Sequence> &y);
37+
38+ template <class T , class Sequence >
39+ bool operator <(const stack<T, Sequence> &x,
40+ const stack<T, Sequence> &y);
41+
42+ template <class T , class Sequence = deque<T>>
43+ class stack {
44+ // 以下三种写法都可以,即标注模板的使用
45+ friend bool operator == <T> (const stack<T> &, const stack<T>&);
46+ friend bool operator < <T> (const stack<T> &, const stack<T> &);
47+
48+ friend bool operator == <T> (const stack &, const stack &);
49+ friend bool operator < <T> (const stack &, const stack &);
50+
51+ friend bool operator == <> (const stack &, const stack &);
52+ friend bool operator < <> (const stack &, const stack &);
53+
54+ // 编译报错,提示如下
55+ // note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here)
56+ // friend bool operator== (const stack &, const stack &);
57+ // friend bool operator< (const stack &, const stack &);
58+
59+ public:
60+ stack () {
61+ cout << " stack" << endl;
62+ }
63+ private:
64+ Sequence c;
65+ };
66+
67+ template <class T , class Sequence >
68+ bool operator ==(const stack<T, Sequence> &x,
69+ const stack<T, Sequence> &y) {
70+ // error: cannot convert 'std::basic_ostream<char>' to 'bool' in return
71+ // return cout << "operator==" << '\t';
72+ cout << " operator==" << ' \t ' ;
73+ return true ;
74+ }
75+
76+ template <class T , class Sequence >
77+ bool operator <(const stack<T, Sequence> &x,
78+ const stack<T, Sequence> &y) {
79+ // return cout << "operator<" << '\t';
80+ cout << " operator<" << ' \t ' ;
81+ return true ;
82+ }
83+
84+ int main () {
85+ stack<int > x;
86+ stack<int > y;
87+
88+ cout << (x == y) << endl;
89+ cout << (x < y) << endl;
90+
91+ stack<char > y1;
92+ // error: no match for 'operator==' (operand types are 'stack<int>' and 'stack<char>')
93+ // cout << (x == y1) << endl;
94+ }
0 commit comments