The difference between C ++ templates and C # generics (C # Programming Guide)

This article is excerpted from the official document of Microsoft C #: The difference between C ++ templates and C # generics (C # Programming Guide)
Both C # generics and C ++ templates are language features that support parameterized types. However, there are many differences between the two. At the syntax level, C # generics are a simpler method of parameterized types, without the complexity of C ++ templates. In addition, C # does not attempt to provide all the features of C ++ templates. At the implementation level, the main difference is that the replacement of C # generic types is performed at runtime, thereby retaining generic type information for instantiated objects. For more information, see Generics in the runtime.
The following are the main differences between C # generics and C ++ templates:

  • The flexibility of C # generics is different from C ++ templates. For example, although you can call user-defined operators in C # generic classes, you cannot call arithmetic operators.
  • C # does not allow the use of non-type template parameters, such as template C {}.
  • C # does not support explicit customization; that is, custom implementation of specific types of templates.
  • C # does not support partial customization: custom implementation of some type parameters.
  • C # does not allow the use of type parameters as a base class for generic types.
  • C # does not allow type parameters to have a default type.
  • In C #, a generic type parameter cannot itself be a generic type, but a constructed type can be used as a generic type. C ++ allows the use of template parameters.
  • C ++ allows code that may not be valid for all type parameters in the template, and then checks this code for the specific type used as the type parameter. C # requires that the code written in the class can handle any type that satisfies the constraints. For example, you can write a function in C ++ that uses the arithmetic operators + and-for objects of type parameters. This function will generate an error when you instantiate a template that has a type that does not support these operators. C # does not allow this operation; the only language constructs allowed are those that can be inferred from constraints.
    See also
  • C # Programming Guide
    Generic Introduction
  • Template (C ++)
Published 131 original articles · Like 38 · Visit 990,000+

Guess you like

Origin blog.csdn.net/ccf19881030/article/details/105607808