Visual C++ .NET/Generics/Generic Function
Содержание
Generic function allows the type parameter to be deduced
#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 );
}
Generic function and generic array
#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 );
}
Generic function demo
#include "stdafx.h"
using namespace System;
generic <typename T>
void F(T t, int i, String^ s)
{
}
generic multiple constraints
#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
{
};
generic return value
#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
}
Specify the type parameter for generic function
#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 );
}