泛型和模板的比较----源自MSDN

2023-11-29 02:58
文章标签 模板 比较 泛型 源自 msdn

本文主要是介绍泛型和模板的比较----源自MSDN,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

                泛型和模板的比较----源自MSDN

 

在我的《主流编程语言优劣考》一文中,有不少朋友对我把“模板”和“泛型”这2个概念作为2个不同的事务来看待有异议。

我告诉他们,在MSDNC++/CLI中就有这样的定义。他们不信。

唉!我就搞不懂了。为什么有些人会这么在意观点、定义的出处呢?

难道不是名人说的,就肯定不是真理吗?难道权威就一定正确吗?

    在这里我把MSDN的原文拿出来给那些朋友看。

 

出自

http://msdn.microsoft.com/zh-cn/library/sbh15dya(en-us,VS.80).aspx

 

MSDN

  • MSDN 主页
  • MSDN 技术资源库
  • MSDN 学习
  • MSDN 下载
  • MSDN 支持
  • MSDN 社区

MSDN Library

  • 开发工具和语言
  • .NET 开发
  • Office Development
  • SQL Server
  • Windows Live
  • 技术文章

<script type=text/Javascript> </script> 语言筛选器 : 全部

Visual Basic

C#

C++

J#

JScript

XAML

<script type=text/Javascript> var ArrowOffPath="http://i.msdn.microsoft.com/Platform/Controls/DropDownFilter/resources/arrow-off.gif"; var ArrowOnPath="http://i.msdn.microsoft.com/Platform/Controls/DropDownFilter/resources/arrow-on.gif"; var strConstLangFilterAll ="全部"; var strConstLangFilterMulti ="多个"; var strConstLangFilterNone ="无"; var strConstLangFilterText ="语言筛选器"; var oMTPS_DD_ImgArrow = document.getElementById("ctl00_rs1_DropDownFilter_MTPS_DD_ImageArrow"); var oMTPS_DD_PanelLink = document.getElementById("ctl00_rs1_DropDownFilter_Mtps_DropDownFilterText"); var oMTPS_DD_Div = document.getElementById("ctl00_rs1_DropDownFilter_DropDownFilterMain"); var oMTPS_DD_PopUpDiv = document.getElementById("ctl00_rs1_DropDownFilter_Mtps_DropDownPopUp"); </script> This page is specific to

Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:

  • .NET Framework 3.0
  • Microsoft Visual Studio 2008/.NET Framework 3.5

Visual C++ Language Reference

Generics and Templates

Generics and templates are both language features that provide support for parameterized types. However, they are different and have different uses. This topic provides an overview of the many differences.

For more information, see Managed Templates and Templates Overview.

Comparing Templates and Generics

Key differences between generics and C++ templates:

·         Generics are generic until the types are substituted for them at runtime. Templates are specialized at compile time so they are not still parameterized types at runtime

·         The common language runtime specifically supports generics in MSIL. Because the runtime knows about generics, specific types can be substituted for generic types when referencing an assembly containing a generic type. Templates, in contrast, resolve into ordinary types at compile time and the resulting types may not be specialized in other assemblies.

·         Generics specialized in two different assemblies with the same type arguments are the same type. Templates specialized in two different assemblies with the same type arguments are considered by the runtime to be different types.

·         Generics are generated as a single piece of executable code which is used for all reference type arguments (this is not true for value types, which have a unique implementation per value type). The JIT compiler knows about generics and is able to optimize the code for the reference or value types that are used as type arguments. Templates generate separate runtime code for each specialization.

·         Generics do not allow non-type template parameters, such as template <int i> C {}. Templates allow them.

·         Generics do not allow explicit specialization (that is, a custom implementation of a template for a specific type). Templates do.

·         Generics do not allow partial specialization (a custom implementation for a subset of the type arguments). Templates do.

·         Generics do not allow the type parameter to be used as the base class for the generic type. Templates do.

·         Generics do not allow type parameters to have default values. Templates do.

·         Templates support template-template parameters (e.g. template<template<class T> class X> class MyClass), but generics do not.

Combining Templates and Generics

·         The basic difference in generics has implications for building applications that combine templates and generics. For example, suppose you have a template class that you want to create a generic wrapper for to expose that template to other languages as a generic. You cannot have the generic take a type parameter that it then passes though to the template, since the template needs to have that type parameter at compile time, but the generic won't resolve the type parameter until runtime. Nesting a template inside a generic won't work either because there's no way to expand the templates at compile time for arbitrary generic types that could be instantiated at runtime.

Example

The following example shows a simple example of using templates and generics together. In this example, the template class passes its parameter through to the generic type. The reverse is not possible.

This idiom could be used when you want to build on an existing generic API with template code that is local to a Visual C++ assembly, or when you need to add an extra layer of parameterization to a generic type, to take advantage of certain features of templates not supported by generics.

复制代码

// templates_and_generics.cpp
// compile with: /clr
using namespace System;
 
generic <class ItemType>
ref class MyGeneric {
   ItemType m_item;
 
public:
   MyGeneric(ItemType item) : m_item(item) {}
   void F() { 
      Console::WriteLine("F"); 
   }
};
 
template <class T>
public ref class MyRef {
MyGeneric<T>^ ig;
 
public:
   MyRef(T t) {
      ig = gcnew MyGeneric<T>(t);
      ig->F();
    }    
};
 
int main() {
   // instantiate the template
   MyRef<int>^ mref = gcnew MyRef<int>(11);
}

Output

F

See Also

Other Resources

Generics (Visual C++)

标记 : 添加标记 添加   取消

标记为 ContentBug

社区内容  

添加新内容

  批注

Using templates to implement generic interfaces

    

Rob Grainger   |   编辑   |   显示历史记录

请稍候  

As a warning, techniques like the one following won't work either...

generic <typename T> public interface class ICollection { void Add(T item); };
class Immutable { bool IsReadOnly() { return true; } };
class Mutable { bool IsReadOnly() { return false; } };
template <typename T, typename M>
ref class MyCollection : public ICollection<T>
{
    typedef M MutType;
public: 
    void Add(T item) { 
        if (MutType::IsReadOnly() throw gcnew NotSupportedException(); 
        internal.Add(item);
    }
    System::Collections::Generic::List<T> internal;
};
public ref class Element { ... };
public ref class FactoryClass
{
    public:
        static ICollection<Element^> CreateMutableCollection() { return gcnew MyCollection<Element^, Mutable>(); }
        static ICollection<Element^> CreateImmutableCollection() { return gcnew MyCollection<Element^, Immutable>(); }
};

Compiling the above, and calling CreateMutableCollection and CreateImmutableCollection from another assembly, always (in my case - I'm not sure the heuristics the compiler used) chose MyCollection<Element^, Mutable>, so it appears that the compiler only instantiates the template once, and uses that instantiation for all references. Shame, as this would be a useful combination of the two techniques, allowing (internally) manufacturing implementations of a generic interface using templates.

 

 

 

 

 

 

 

 

 

 

 

这篇关于泛型和模板的比较----源自MSDN的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/431189

相关文章

C++的模板(八):子系统

平常所见的大部分模板代码,模板所传的参数类型,到了模板里面,或实例化为对象,或嵌入模板内部结构中,或在模板内又派生了子类。不管怎样,最终他们在模板内,直接或间接,都实例化成对象了。 但这不是唯一的用法。试想一下。如果在模板内限制调用参数类型的构造函数会发生什么?参数类的对象在模板内无法构造。他们只能从模板的成员函数传入。模板不保存这些对象或者只保存他们的指针。因为构造函数被分离,这些指针在模板外

记录AS混淆代码模板

开启混淆得先在build.gradle文件中把 minifyEnabled false改成true,以及shrinkResources true//去除无用的resource文件 这些是写在proguard-rules.pro文件内的 指定代码的压缩级别 -optimizationpasses 5 包明不混合大小写 -dontusemixedcaseclassnames 不去忽略非公共

比较学习难度:Adobe Illustrator、Photoshop和新兴在线设计平台

从入门设计开始,几乎没有人不知道 Adobe 公司两大设计软件:Adobe Illustrator和 Photoshop。虽然AI和PS很有名,有一定设计经验的设计师可以在早期探索和使用后大致了解AI和PS的区别,但似乎很少有人会系统地比较AI和PS。目前,设计软件功能多样,轻量级和网页设计软件已成为许多设计师的需求。对于初学者来说,一篇有针对性的AI和PS比较总结文章具有非常重要的指导意义。毕竟

Python几种建表方法运行时间的比较

建立一个表[0,1,2,3.......10n],下面几种方法都能实现,但是运行时间却截然不同哦 import time#方法一def test1(n):list=[]for i in range(n*10):list=list+[i]return list#方法二def test2(n):list=[]for i in range(n*10):list.append(i)#方法三d

C++标准模板库STL介绍

STL的六大组成部分 STL(Standard Template Library)是 C++ 标准库中的一个重要组成部分,提供了丰富的通用数据结构和算法,使得 C++ 编程变得更加高效和方便。STL 包括了 6 大类组件,分别是算法(Algorithm)、容器(Container)、空间分配器(Allocator)、迭代器(Iterator)、函数对象(Functor)、适配器(Adapter)

HTML5文旅文化旅游网站模板源码

文章目录 1.设计来源文旅宣传1.1 登录界面演示1.2 注册界面演示1.3 首页界面演示1.4 文旅之行界面演示1.5 文旅之行文章内容界面演示1.6 关于我们界面演示1.7 文旅博客界面演示1.8 文旅博客文章内容界面演示1.9 联系我们界面演示 2.效果和源码2.1 动态效果2.2 源代码2.3 源码目录 源码下载万套模板,程序开发,在线开发,在线沟通 作者:xcLeigh

静态文件及模板

自学python如何成为大佬(目录):https://blog.csdn.net/weixin_67859959/article/details/139049996?spm=1001.2014.3001.5501 1  静态文件 动态Web应用也会需要静态文件,通常是CSS和JavaScript文件。Flask可以向已经配置好的Web服务器提供静态文件,只要在包或模块所在的目录中创建一个名为s

周末设计高端企业_集团官网主题Discuz模板

风格名称: 周末设计_高端企业_集团官网 适用版本: Discuz! X3.0、X3.1、X3.2、X3.3、F1.0 风格编码: 使用语言包结构,适合全部编码 周末设计高端企业_集团官网主题Discuz模板

Struts2与struts1与springmvc比较

最近做项目用到了struts2,之前一直是用struts1和springMVC。感觉到了struts2从很大程度上和这两个还是有很大区别的,所以今天搜集了些资料,给他们做一下对比。            Struts1官方已经停止更新,现在用的也比较少,这里主要讲一下struts2和struts1比较都有哪些不同和进步。Struts2可以说不是完全从struts1改进来的,因为

算法8—不通过比较,找出两个数的最大值

问题: 比如:给定两个值 5和10,不通过比较,直接找出最大值。 分析: 一旦涉及到不用比较找最大值,想都不用想,一般只能通过位运算来实现。  max = a - ((a-b)&((a-b)>>31)) 或者 max = ((a+b)+|a-b|)/2 如果找最小值,我们只需把两个值相加,减去max即可。