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

相关文章

百度/小米/滴滴/京东,中台架构比较

小米中台建设实践 01 小米的三大中台建设:业务+数据+技术 业务中台--从业务说起 在中台建设中,需要规范化的服务接口、一致整合化的数据、容器化的技术组件以及弹性的基础设施。并结合业务情况,判定是否真的需要中台。 小米参考了业界优秀的案例包括移动中台、数据中台、业务中台、技术中台等,再结合其业务发展历程及业务现状,整理了中台架构的核心方法论,一是企业如何共享服务,二是如何为业务提供便利。

poj3468(线段树成段更新模板题)

题意:包括两个操作:1、将[a.b]上的数字加上v;2、查询区间[a,b]上的和 下面的介绍是下解题思路: 首先介绍  lazy-tag思想:用一个变量记录每一个线段树节点的变化值,当这部分线段的一致性被破坏我们就将这个变化值传递给子区间,大大增加了线段树的效率。 比如现在需要对[a,b]区间值进行加c操作,那么就从根节点[1,n]开始调用update函数进行操作,如果刚好执行到一个子节点,

C++11第三弹:lambda表达式 | 新的类功能 | 模板的可变参数

🌈个人主页: 南桥几晴秋 🌈C++专栏: 南桥谈C++ 🌈C语言专栏: C语言学习系列 🌈Linux学习专栏: 南桥谈Linux 🌈数据结构学习专栏: 数据结构杂谈 🌈数据库学习专栏: 南桥谈MySQL 🌈Qt学习专栏: 南桥谈Qt 🌈菜鸡代码练习: 练习随想记录 🌈git学习: 南桥谈Git 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈�

poj 1258 Agri-Net(最小生成树模板代码)

感觉用这题来当模板更适合。 题意就是给你邻接矩阵求最小生成树啦。~ prim代码:效率很高。172k...0ms。 #include<stdio.h>#include<algorithm>using namespace std;const int MaxN = 101;const int INF = 0x3f3f3f3f;int g[MaxN][MaxN];int n

uva 1342 欧拉定理(计算几何模板)

题意: 给几个点,把这几个点用直线连起来,求这些直线把平面分成了几个。 解析: 欧拉定理: 顶点数 + 面数 - 边数= 2。 代码: #include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#include <cstring>#include <cmath>#inc

uva 11178 计算集合模板题

题意: 求三角形行三个角三等分点射线交出的内三角形坐标。 代码: #include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#include <cstring>#include <cmath>#include <stack>#include <vector>#include <

poj 2104 and hdu 2665 划分树模板入门题

题意: 给一个数组n(1e5)个数,给一个范围(fr, to, k),求这个范围中第k大的数。 解析: 划分树入门。 bing神的模板。 坑爹的地方是把-l 看成了-1........ 一直re。 代码: poj 2104: #include <iostream>#include <cstdio>#include <cstdlib>#include <al

最大流、 最小费用最大流终极版模板

最大流  const int inf = 1000000000 ;const int maxn = 20000 , maxm = 500000 ;struct Edge{int v , f ,next ;Edge(){}Edge(int _v , int _f , int _next):v(_v) ,f(_f),next(_next){}};int sourse , mee

关键字synchronized、volatile的比较

关键字volatile是线程同步的轻量级实现,所以volatile性能肯定比synchronized要好,并且volatile只能修饰于变量,而synchronized可以修饰方法,以及代码块。随着JDK新版本的发布,synchronized关键字的执行效率上得到很大提升,在开发中使用synchronized关键字的比率还是比较大的。多线程访问volatile不会发生阻塞,而synchronize

C++语法知识点合集:11.模板

文章目录 一、非类型模板参数1.非类型模板参数的基本形式2.指针作为非类型模板参数3.引用作为非类型模板参数4.非类型模板参数的限制和陷阱:5.几个问题 二、模板的特化1.概念2.函数模板特化3.类模板特化(1)全特化(2)偏特化(3)类模板特化应用示例 三、模板分离编译1.概念2.模板的分离编译 模版总结 一、非类型模板参数 模板参数分类类型形参与非类型形参 非类型模板