Imitation of Java Generics

Posted on: 31/12/2010

Generic programming is very common and has different names (and features) in various programming languages; C++ provides Turing-Complete Templates, Java offers Generics (along with Ada, Eiffel, C#, and Visual Basic .Net), and Parametric Polymorphism is present in ML, Scala, and Haskell.

While I am generally pretty happy with what C++ has to offer, adopting some of the features offered by other mechanisms can come in handy sometimes. To be more specific, in this post we will mimic Java’s support for defining an upper bound for generic elements (i.e. List<T extends Comparable>).

The task at hand is the implementation of a priority queue, which is essentially a heap. Sure enough, the priority queue will have a parametric (template) type T, which will have to be Comparable. Something along the lines of:

template <typename T>
struct priority_queue {
    // ...

Keep in mind that we will have to do one of two things:

  • Either clearly state in the documentation that the implementation of our priority_queue heavily relies on type T having implemented operator<,
  • Or add another parametric (template) type F, to serve as a Comparator.

Both things may seem a little far from optimal. Have we gone with Java in the first place, all we would have had to do would have been something closely resembling the following:

class priority_queue<T extends Comparable>

As it turns out, the same effect (although with slightly different syntax) can actually be achieved even in C++, through utilization of two boost utilities: is_base_of and static_assert. A brief sketch is hereby presented:

struct Comparable {
    // required API..

template <typename T>
class priority_queue {
    // Ask compiler to enforce that T is a subtype of Comparable:
    BOOST_STATIC_ASSERT(boost::is_base_of<Comparable, T>::value);

A colleague of mine walked up to me some time ago and asked why isn’t such a mechanism included in C++’s core features. After putting some more thought into it, I have come up to the conclusion that I would actually hate seeing such a built-in C++ feature – In my opinion, it will lead to an excessive number of not-general-enough base classes, which are only there to feed this mechanism. Moreover, it is very likely to lead to much more abuse of the multiple inheritance mechanism.

The C++0x standard draft presented a related feature named Concepts (and Concept-maps), which were recently dropped as well.

What do you think?


6 Responses to "Imitation of Java Generics"

Your example would certainly result an unnecessary amount of base classes in C++. This is largely because in C++ there is no such thing as an interface or a mixin. In Java, this works because Comparable is an interface (implements not extends).

I think you have not understood java generics, nor C++ concepts.

Java generics relies on introspection, and through introspection loses all its face value.

C++ concepts are an attempt to mimic part of haskell classes, and it´s been dropped mainly on the difficulty to agree how tio implement them, not on a basis on not seeing it as useful. In fact, it has only been delayed.

As you see, Java generics are checked at compile-time and easily bypassavbble at run-time, while concepts do force checking at compile-time, but are not bypassable as they do not create any run-time artifact. Just like Haskell classes.

I think it is an error to put all these different ideas under a misnomer as ‘generic programming’.

As Zara said, you seem to be underestimating concepts. Concepts were supposed to be non-intrusive, you wouldn’t have to derive your class from Comparable it would be deduced automatically from the concept.

auto concept Comparable<typename T> {
    bool operator<(const T&, const T&);

And you could also adapt types to meet the static interface.

concept_map Comparable {
   bool operator<(const SomeType& lhs, const SomeType&rhs) { 
      return lhs.IsLessThan(rhs);

Your example is rewritten in C++ using static interface.
Like it is done in std:: classes .

template <typename T, typename Compare = std::less >
class priority_queue;

I don’t remember myself needing this type check so often.

Since C++ doesn’t have a standard interfaces like Comparable, in most cases you rely on compile-time interface.

And this is why C++ programmers laugh when Java programmers talk about object models and what could be stripped away without loss.

I would like to add to your view of generics that apart from problems like clumsy interface (we require unnecessary inheritance) and some safety issues, they have obvious advantages over templates, at least when it comes to defining generic containers:
1. No cryptic error messages.
2. Much faster compilation – a generic can be compiled once, regardless of how many times you instantiate it and with how many types.
3. Smaller executable – each template instantiation generates almost the same code time and again – this is not so for generics

That said, I would also not like to see generics in C++. You can still implement something similar yourself using templates.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: