Generics and Templates (C++/CLI)

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 Windows Runtime and Managed Templates.

Comparing Templates and Generics

Key differences between generics and C++ templates:

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

Description

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 C++/CLI 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.

Code

// 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); } F

See also

Generics

Link nội dung: https://hauionline.edu.vn/template-cau-hoi-a105781.html