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

C++ Equivalent to Java Generics

Java generics and C++ templates are implemented in totally different ways - Java generics uses the concept of 'type erasure' (compiling to Object and casts), while C++ templates result in separate classes created at compile-time, but you can usually achieve the same result by converting one to the other.

Creating a List

Java C++
ArrayList<Integer> myVar = new ArrayList<Integer>(); std::vector<int> myVar;

Creating a Dictionary

Java C++
HashMap<String, Integer> myVar = new HashMap<String, Integer>(); std::unordered_map<std::string, int> myVar;

Defining a Generic Class

Java C++
public class GenericClass<T>
{
}
template<typename T>
class GenericClass
{
};

Defining a Generic Class with a Constraint

Java C++
public class GenericClass<T extends 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 Method

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

Defining a Generic Method with a Constraint

Java C++
public <T extends SomeBase> int Compare(T param1, T param2)
{
}
#include <type_traits>

public:
template<typename T>
int Compare(T param1, T param2)
{
    static_assert(std::is_base_of<SomeBase, T>::value, "T must inherit from SomeBase");
}


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

Additional resource: Java and C++ Equivalents


Copyright © 1997 – 2017 Tangible Software Solutions Inc.