[C++]类模板在何时实例化?
2015-12-11 16:40
351 查看
影响中的一道笔试题,总结了下模板类只声明未定义时,在哪些情况会出现编译错误。
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
FROM: http://www.cppblog.com/Code-L/articles/132805.html?opt=admin
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
FROM: http://www.cppblog.com/Code-L/articles/132805.html?opt=admin
相关文章推荐
- C++第11版本中的一些强大的新特性小结
- C++多态技术的实现和反思
- vs2010 C++静态编译
- C++ Primer Plus第六版 第十六章 编程练习答案
- Loadruuner C语言脚本--如何引用DLL文件
- c++实现hashtable缓存
- 博弈——翻硬币游戏
- C#做界面果然比C++方便
- C++中的临时对象 zz
- C语言实现文件之间内容的复制
- c++ builder xe2 字符串转日期
- c++ builder xe2 debug正常 release崩溃 解决一例
- 算法:阿克曼函数(C++)
- C++代码质量检查工具-----Cpplint
- 算法:汉诺塔问题(c++)
- C语言实现GBK/GB2312/五大码之间的转换(转)
- C++内存管理详解
- 算法:二分查找算法(c++)
- 算法之排序算法:插入排序(C++)
- 关于理解指针与函数