• Saves Valuable Time
  • Trusted Accuracy for 12 Years
  • 15-Day Money-Back Guarantee

C++ Equivalent to C# Generics

C# generics and C++ templates are implemented in totally different ways - C# generics is a runtime feature, while C++ templates result in separate classes created at compile-time, but you can still often achieve the same result by converting one to the other.

Creating a List

C# C++
List<int> myVar = new List<int>(); std::vector<int> myVar;

Creating a Dictionary

C# C++
Dictionary<string, int> myVar = new Dictionary<string, int>(); std::unordered_map<std::string, int> myVar;

Defining a Generic Class

C# C++
public class GenericClass<T> template<typename T>
class GenericClass

Defining a Generic Class with a Constraint

C# C++
public class GenericClass<T> where T: SomeBase #include <type_traits>

template<typename T>
class GenericClass
{
    static_assert(std::is_base_of<SomeBase, T>::value, "T must inherit from SomeBase");
};

Defining a Generic Class with a 'new' Constraint

C# C++
public class GenericClass<T> where T: new() #include <type_traits>

template<typename T>
class GenericClass
{
    static_assert(std::is_default_constructible<T>::value, "T requires default-constructible elements");
};

Defining a Generic Method

C# C++
public int Compare<T>(T param1, T param2) public:
template<typename T>
int Compare(T param1, T param2)

Defining a Generic Method with a Constraint

C# C++
public void Swap<T>(ref T l, ref T r) where T: class #include <type_traits>

public:
template<typename T>
void Swap(T &l, T &r)
{
    static_assert(std::is_class<T>::value, "T must be a class");
}


Use C# to C++ Converter to convert from C# to C++.     

Additional resource: C++ and C# Equivalents


Copyright © 1997 – 2017 Tangible Software Solutions Inc.