Visual C++ .NET/Generics/Generic Function

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Generic function allows the type parameter to be deduced

<source lang="csharp">

  1. include "stdafx.h"

using namespace System; generic < typename T> void GenericFunction(T t) {

  Console::WriteLine(t);

} int main() {

  int i;
  GenericFunction<int>( 200 );
  GenericFunction( 400 );

}

 </source>


Generic function and generic array

<source lang="csharp">

  1. include "stdafx.h"

using namespace System; generic < typename T> void GenericFunction(array<T>^ array_of_t) {

  for each (T t in array_of_t)
  {
     Console::WriteLine(t);
  }

} int main() {

  array<String^>^ array_of_string;
  array_of_string = gcnew array<String^>{ "abc", "def", "ghi" };
  GenericFunction( array_of_string );

}

 </source>


Generic function demo

<source lang="csharp">

  1. include "stdafx.h"

using namespace System; generic <typename T> void F(T t, int i, String^ s) { }

 </source>


generic multiple constraints

<source lang="csharp">

  1. include "stdafx.h"

using namespace System; interface class I; ref class C; generic <class T> where T : gcnew(), C, I void F(T t) { } interface class IKey; generic <typename Key, typename Value> where Key : IKey where Value : value class ref class Dictionary { };

 </source>


generic return value

<source lang="csharp">

  1. include "stdafx.h"

using namespace System; generic <typename T> T f() {

  return T();

} int main() {

 int i = f<int>();  // OK
 String^ s = f<String^>();  // OK

}

 </source>


Specify the type parameter for generic function

<source lang="csharp">

  1. include "stdafx.h"

using namespace System; generic < typename T> void GenericFunction(T t) {

  Console::WriteLine(t);

} int main() {

  int i;
  GenericFunction<int>( 200 );
  GenericFunction( 400 );

}

 </source>