Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's a c++ equivalent of a generic?

suppose i'm implementing a polymorphic tree data structure that can take on data of any type...

Tree<Int> or Tree<String> or Tree<Object>

but I'm implementing it in C++....how would I specify that the tree can contain an arbitrary type similar to generics in Java

also is there an equivalent of Java's Object object in C++ in which all objects in C++ inherits Object

like image 467
kamikaze_pilot Avatar asked Apr 10 '11 14:04

kamikaze_pilot


People also ask

What is generic type?

A generic type is a generic class or interface that is parameterized over types. The following Box class will be modified to demonstrate the concept.

What is generics in Java with example?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.

Why are generics so important?

Generics enable the use of stronger type-checking, the elimination of casts, and the ability to develop generic algorithms. Without generics, many of the features that we use in Java today would not be possible.


1 Answers

The nearest equivalent of Java's generic is template in C++. Its not equivalent as such, if strictly speaking. But that is what you've in C++. So to suit your need, you've to work a little bit so that you can write equivalent code in C++.

Here're few links to some articles that compare C++ template with Java generics:

  • Java Generics and C++ Templates (at Dr Dobbs)
  • Generics in C#, Java, and C++ (at artima.com)
like image 93
Nawaz Avatar answered Sep 21 '22 17:09

Nawaz