[C++]类模板在何时实例化?

本文探讨了当模板类仅声明而未定义时,在不同情况下出现编译错误的现象。指出直接实例化对象、函数定义中非引用实例化模板对象等场景会导致编译错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

影响中的一道笔试题,总结了下模板类只声明未定义时,在哪些情况会出现编译错误。
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> *= 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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值