您的位置:首页 > 其它

泛型和模板的比较----源自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.

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

Generics(VisualC++)

标记:添加标记添加取消

标记为ContentBug

社区内容

添加新内容

批注

Usingtemplatestoimplementgenericinterfaces

RobGrainger|编辑|显示历史记录

请稍候

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: