影响中的一道笔试题,总结了下模板类只声明未定义时,在哪些情况会出现编译错误。
1、直接实例化对象(只是声明则不会出错),无论用栈还是new,编译时都会出错。
2、函数定义(只是声明则不会编译错误)中参数或返回值引用实例化该模板对象时,非引用和传指针,编译时会出错。
总结:
定义中直接使用类模板的实例模板类而非引用,则在编译时就会对其实例化,因为本例中该类模板只有声明没有定义,所以编译时就会出错
1 /**
2 * Copyright 2010 Lei Hu. All rights reserved.
3 * Lei Hu PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
4 */
5 #include <iostream>
6 using namespace std;
7
8 template <typename T> class A;
9
10 extern A<char> g; // ok, just declare.
11
12 void f1(A<int> p) // error, undefined type 'A<int>'
13 {
14
15 }
16
17 template <typename T>
18 void f2(A<T> p); // ok.
19
20 void f3(A<int> &p) // ok, reference or pointer.
21 {
22
23 }
24
25 template <typename T>
26 void f4(A<T> p) // ok, template non-instance.
27 {
28
29 }
30
31 A<int> f5(); // ok, just declare function.
32
33 A<int> f6() // error, use of undefined type 'A<int>'
34 {
35
36 }
37
38 template <typename T>
39 A<T> f7() // ok, template non-instance
40 {
41
42 }
43
44 void main()
45 {
46 A<char> *a = NULL;
47 A<char> b; // error, uses undefined class 'A<char>'
48 }
49