tags:

views:

142

answers:

4

I am little confused on how templates in c++ and generics in java work. it would be helpful if someone explained me how this java code will be c++:

public class Box<T> {

    private T t;          

    public void add(T t1) {
        this.t = t1;
    }

    public T get() {
        return t;
    }

    public <U> void inspect(U u){
        System.out.println("T: " + t.getClass().getName());
        System.out.println("U: " + u.getClass().getName());
    }

    public static void main(String[] args) {
        Box<Integer> integerBox = new Box<Integer>();
        integerBox.add(new Integer(10));
        integerBox.inspect(10);
    }
}
A: 

I don't think SO is the place to get a real answer to this question, as there are LOTS of reference sites available on the web, and a sufficient answer would require a lot of typing. That said, you should be aware that C++ templates and Java generics are VERY different. They may look the same but completely different rules apply. C++ generates code for each specialization, while Java discards type information at runtime and generates implicit safe casts. Apples and Oranges. Actually, more like Kumquats and Screwdrivers.

Jim Garrison
+4  A: 
#include <iostream>
#include <typeinfo>

template <class T>
class Box {
 public:
    void add(const T &t1) { t = t1; }

    T get() const { return t; }

    template <class U>
    void inspect(const U &u) const {
        ::std::cout << "T: " << typeid(t).name() << "\n";
        ::std::cout << "U: " << typeid(u).name() << "\n";
    }

 private:
    T t;
};

int main(int argc, const char *argv[])
{
    Box<int> integerBox;
    integerBox.add(10);
    integerBox.inspect(10);
    return 0;
}

That's a rough translation. I took some license since you must use a reference/pointer to refer to any object in Java where in C++ you can just have it right there. But that's basically it.

If you wish to be further confused, you can have this for main:

#include <string> // You could put this line at the top of the file,
                  // but it doesn't have to be there.

int main(int argc, const char *argv[])
{
    Box<int> integerBox;
    Box< ::std::string > stringBox;
    integerBox.add(10);
    integerBox.inspect(10);
    stringBox.add("Hello World!");
    stringBox.inspect("Hello World!");
    return 0;
}

Mostly I think you will find the output of stringBox.inspect("Hello World!"); to be most perplexing.

Omnifarious
God that looks horrible. Good thing I never touched C++
TheLQ
@Lord Quackstar: You are entitled to your opinion. Personally, I feel very similarly about Java.
Omnifarious
@Omnifarious: Fair enough.
TheLQ
+3  A: 

Actually you can regard C++ templates and Java Generics as polar opposites.

C+ templates create new types.

Java Generics restrict existing types.

EJP
A: 

I have written a blog article some time ago, quickly summarizing the difference between Java generics and C++ templates which you may also be interested in: this blog post

The process of setting the type of the class template (in C++) or generic is called template specialization or generics specialization. From a first point of view generics and c++ templates may look very similar, but what's important is how the compiler translates it under the hood.

Java generics simply offer compile-time safety and eliminate the need for casts. They are implemented directly by the Java compiler as a front-end conversion, also known as type erasure. The compiler basically just erases all generic specifications (between the angle brackets) and inserts casts where necessary. Moreover it keeps track of the generics internally such that all instantiations will use the same underlying generic class at compile/run time. It is therefore somehow a process of code translation or rewriting.

A C++ template gets reproduced (code generation) and re-compiled entirely whenever a template is instantiated with a new class. This may have an impact onto performance. Moreover potential errors are spotted at the last possible moment, at run-time when things are being used, i.e. when templates are being instantiated and used.

Java generics give you compile-time safety.

Juri
Please don't use minified urls.
Alexandre C.
@Alexandre gets automatically copied this way by an extension, but just for curiosity: why shouldn't I use them?
Juri
@Juri: Because readers don't know what they are pointing to. See http://meta.stackoverflow.com/questions/29518/can-and-should-stack-overflow-automatically-rewrite-bit-ly-links
Alexandre C.
It doesn't 'keep track of the genetics internally such that all instantiations will use the same underlying generic class'. There *is* only one underlying class: that's the whole point of type erasure.
EJP