泛型和模板的比较----源自MSDN
2008-08-04 00:09
239 查看
泛型和模板的比较----源自MSDN
在我的《主流编程语言优劣考》一文中,有不少朋友对我把“模板”和“泛型”这2个概念作为2个不同的事务来看待有异议。
我告诉他们,在MSDN的C++/CLI中就有这样的定义。他们不信。
唉!我就搞不懂了。为什么有些人会这么在意观点、定义的出处呢?
难道不是名人说的,就肯定不是真理吗?难道权威就一定正确吗?
在这里我把MSDN的原文拿出来给那些朋友看。
出自
http://msdn.microsoft.com/zh-cn/library/sbh15dya(en-us,VS.80).aspx
MSDN
MSDN主页
MSDN技术资源库
MSDN学习
MSDN下载
MSDN支持
MSDN社区
MSDNLibrary
开发工具和语言
.NET开发
OfficeDevelopment
SQLServer
WindowsLive
技术文章
语言筛选器:全部
VisualBasic
C#
C++
J#
JScript
XAML
Thispageisspecificto
MicrosoftVisualStudio2005/.NETFramework2.0
Otherversionsarealsoavailableforthefollowing:
.NETFramework3.0
MicrosoftVisualStudio2008/.NETFramework3.5
VisualC++LanguageReference
GenericsandTemplates
Genericsandtemplatesarebothlanguagefeaturesthatprovidesupportforparameterizedtypes.However,theyaredifferentandhavedifferentuses.Thistopicprovidesanoverviewofthemanydifferences.
Formoreinformation,seeManagedTemplatesandTemplatesOverview.
·Genericsaregenericuntilthetypesaresubstitutedforthematruntime.Templatesarespecializedatcompiletimesotheyarenotstillparameterizedtypesatruntime
·ThecommonlanguageruntimespecificallysupportsgenericsinMSIL.Becausetheruntimeknowsaboutgenerics,specifictypescanbesubstitutedforgenerictypeswhenreferencinganassemblycontainingagenerictype.Templates,incontrast,resolveintoordinarytypesatcompiletimeandtheresultingtypesmaynotbespecializedinotherassemblies.
·Genericsspecializedintwodifferentassemblieswiththesametypeargumentsarethesametype.Templatesspecializedintwodifferentassemblieswiththesametypeargumentsareconsideredbytheruntimetobedifferenttypes.
·Genericsaregeneratedasasinglepieceofexecutablecodewhichisusedforallreferencetypearguments(thisisnottrueforvaluetypes,whichhaveauniqueimplementationpervaluetype).TheJITcompilerknowsaboutgenericsandisabletooptimizethecodeforthereferenceorvaluetypesthatareusedastypearguments.Templatesgenerateseparateruntimecodeforeachspecialization.
·Genericsdonotallownon-typetemplateparameters,suchastemplate<inti>C{}.Templatesallowthem.
·Genericsdonotallowexplicitspecialization(thatis,acustomimplementationofatemplateforaspecifictype).Templatesdo.
·Genericsdonotallowpartialspecialization(acustomimplementationforasubsetofthetypearguments).Templatesdo.
·Genericsdonotallowthetypeparametertobeusedasthebaseclassforthegenerictype.Templatesdo.
·Genericsdonotallowtypeparameterstohavedefaultvalues.Templatesdo.
·Templatessupporttemplate-templateparameters(e.g.template<template<classT>classX>classMyClass),butgenericsdonot.
ThisidiomcouldbeusedwhenyouwanttobuildonanexistinggenericAPIwithtemplatecodethatislocaltoaVisualC++assembly,orwhenyouneedtoaddanextralayerofparameterizationtoagenerictype,totakeadvantageofcertainfeaturesoftemplatesnotsupportedbygenerics.
复制代码
Generics(VisualC++)
标记:添加标记添加取消
标记为ContentBug
请稍候
Asawarning,techniquesliketheonefollowingwon'tworkeither...
Compilingtheabove,andcallingCreateMutableCollectionandCreateImmutableCollectionfromanotherassembly,always(inmycase-I'mnotsuretheheuristicsthecompilerused)choseMyCollection<Element^,Mutable>,soitappearsthatthecompileronlyinstantiatesthetemplateonce,andusesthatinstantiationforallreferences.Shame,asthiswouldbeausefulcombinationofthetwotechniques,allowing(internally)manufacturingimplementationsofagenericinterfaceusingtemplates.
在我的《
我告诉他们,在MSDN的C++/CLI中就有这样的定义。他们不信。
唉!我就搞不懂了。为什么有些人会这么在意观点、定义的出处呢?
难道不是名人说的,就肯定不是真理吗?难道权威就一定正确吗?
在这里我把MSDN的原文拿出来给那些朋友看。
出自
VisualBasic
C#
C++
J#
JScript
XAML
Thispageisspecificto
MicrosoftVisualStudio2005/.NETFramework2.0
Otherversionsarealsoavailableforthefollowing:
VisualC++LanguageReference
GenericsandTemplates
Genericsandtemplatesarebothlanguagefeaturesthatprovidesupportforparameterizedtypes.However,theyaredifferentandhavedifferentuses.Thistopicprovidesanoverviewofthemanydifferences.
Formoreinformation,see
ComparingTemplatesandGenerics
KeydifferencesbetweengenericsandC++templates:·Genericsaregenericuntilthetypesaresubstitutedforthematruntime.Templatesarespecializedatcompiletimesotheyarenotstillparameterizedtypesatruntime
·ThecommonlanguageruntimespecificallysupportsgenericsinMSIL.Becausetheruntimeknowsaboutgenerics,specifictypescanbesubstitutedforgenerictypeswhenreferencinganassemblycontainingagenerictype.Templates,incontrast,resolveintoordinarytypesatcompiletimeandtheresultingtypesmaynotbespecializedinotherassemblies.
·Genericsspecializedintwodifferentassemblieswiththesametypeargumentsarethesametype.Templatesspecializedintwodifferentassemblieswiththesametypeargumentsareconsideredbytheruntimetobedifferenttypes.
·Genericsaregeneratedasasinglepieceofexecutablecodewhichisusedforallreferencetypearguments(thisisnottrueforvaluetypes,whichhaveauniqueimplementationpervaluetype).TheJITcompilerknowsaboutgenericsandisabletooptimizethecodeforthereferenceorvaluetypesthatareusedastypearguments.Templatesgenerateseparateruntimecodeforeachspecialization.
·Genericsdonotallownon-typetemplateparameters,suchastemplate<inti>C{}.Templatesallowthem.
·Genericsdonotallowexplicitspecialization(thatis,acustomimplementationofatemplateforaspecifictype).Templatesdo.
·Genericsdonotallowpartialspecialization(acustomimplementationforasubsetofthetypearguments).Templatesdo.
·Genericsdonotallowthetypeparametertobeusedasthebaseclassforthegenerictype.Templatesdo.
·Genericsdonotallowtypeparameterstohavedefaultvalues.Templatesdo.
·Templatessupporttemplate-templateparameters(e.g.template<template<classT>classX>classMyClass),butgenericsdonot.
CombiningTemplatesandGenerics
·Thebasicdifferenceingenericshasimplicationsforbuildingapplicationsthatcombinetemplatesandgenerics.Forexample,supposeyouhaveatemplateclassthatyouwanttocreateagenericwrapperfortoexposethattemplatetootherlanguagesasageneric.Youcannothavethegenerictakeatypeparameterthatitthenpassesthoughtothetemplate,sincethetemplateneedstohavethattypeparameteratcompiletime,butthegenericwon'tresolvethetypeparameteruntilruntime.Nestingatemplateinsideagenericwon'tworkeitherbecausethere'snowaytoexpandthetemplatesatcompiletimeforarbitrarygenerictypesthatcouldbeinstantiatedatruntime.Example
Thefollowingexampleshowsasimpleexampleofusingtemplatesandgenericstogether.Inthisexample,thetemplateclasspassesitsparameterthroughtothegenerictype.Thereverseisnotpossible.ThisidiomcouldbeusedwhenyouwanttobuildonanexistinggenericAPIwithtemplatecodethatislocaltoaVisualC++assembly,orwhenyouneedtoaddanextralayerofparameterizationtoagenerictype,totakeadvantageofcertainfeaturesoftemplatesnotsupportedbygenerics.
//templates_and_generics.cpp
//compilewith:/clr
usingnamespaceSystem;
generic<classItemType>
refclassMyGeneric{
ItemTypem_item;
public:
MyGeneric(ItemTypeitem):m_item(item){}
voidF(){
Console::WriteLine("F");
}
};
template<classT>
publicrefclassMyRef{
MyGeneric<T>^ig;
public:
MyRef(Tt){
ig=gcnewMyGeneric<T>(t);
ig->F();
}
};
intmain(){
//instantiatethetemplate
MyRef<int>^mref=gcnewMyRef<int>(11);
}
Output
F
SeeAlso
OtherResources
标记
标记为
社区内容 |
Usingtemplatestoimplementgenericinterfaces | |||
Asawarning,techniquesliketheonefollowingwon'tworkeither...
generic<typenameT>publicinterfaceclassICollection{voidAdd(Titem);};
classImmutable{boolIsReadOnly(){returntrue;}};
classMutable{boolIsReadOnly(){returnfalse;}};
template<typenameT,typenameM>
refclassMyCollection:publicICollection<T>
{
typedefMMutType;
public:
voidAdd(Titem){
if(MutType::IsReadOnly()throwgcnewNotSupportedException();
internal.Add(item);
}
System::Collections::Generic::List<T>internal;
};
publicrefclassElement{...};
publicrefclassFactoryClass
{
public:
staticICollection<Element^>CreateMutableCollection(){returngcnewMyCollection<Element^,Mutable>();}
staticICollection<Element^>CreateImmutableCollection(){returngcnewMyCollection<Element^,Immutable>();}
};
Compilingtheabove,andcallingCreateMutableCollectionandCreateImmutableCollectionfromanotherassembly,always(inmycase-I'mnotsuretheheuristicsthecompilerused)choseMyCollection<Element^,Mutable>,soitappearsthatthecompileronlyinstantiatesthetemplateonce,andusesthatinstantiationforallreferences.Shame,asthiswouldbeausefulcombinationofthetwotechniques,allowing(internally)manufacturingimplementationsofagenericinterfaceusingtemplates.
相关文章推荐
- 泛型和模板的比较----源自MSDN
- Java 中的泛型与 C++ 模板的比较
- Java 中的泛型与 C++ 模板的比较
- Java 中的泛型与 C++ 模板的比较
- C++ 模板类型萃取技术 第二部分 基于泛型的类型萃取技术
- C#中泛型的协变与逆变的理解【转】(比较容易理解)
- C#笔记25:比较和排序(IComparable和IComparer以及它们的泛型实现)
- c#初学-泛型ArrayList的使用和List<T>的比较
- HDU 3549 Flow Problem(最大流+EK邻接表||邻接矩阵||dinic算法模板比较)
- .net泛型,数组,lambda调用性能 定量比较
- dao持久层通用泛型接口模板
- 泛型字典类比较
- JAVA 泛型方法比较
- Java 容器 & 泛型(2):ArrayList 、LinkedList和Vector比较
- 结合泛型与模板的STL.NET
- 用Astar(A*)算法 实现的迷宫最短路。代码比较规范,可作为模板
- C++与C#对比学习:模板,泛型
- C++学习笔记57——非类型模板形参与泛型代码原则
- Java的List模板类型与C++的list模板类型的比较
- 自己写的ASP模板解析程序,比较烂