0

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);
    }
}
2
  • 1
    Are you confused about generics in general? Or about the differences between generic programming in Java and in C++? If you're concerned about the latter, see What are the differences between “generic” types in C++ and Java? Commented Aug 10, 2010 at 2:28
  • 1
    I think you are asking the wrong question if you want to understand templates. Java generics and C++ templates, despite having very similar looking syntax, are only vaguely similar constructs and more different than alike. And your example also relies on autoboxing, which is null concept in C++. C++ doesn't have autoboxing and never would because it would make no sense. The closest C++ gets is automatic conversions, but they aren't really very similar to autoboxing. Commented Aug 10, 2010 at 3:31

4 Answers 4

4
#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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

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

C+ templates create new types.

Java Generics restrict existing types.

Comments

0

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.

Comments

0

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.

4 Comments

Please don't use minified urls.
@Alexandre gets automatically copied this way by an extension, but just for curiosity: why shouldn't I use them?
Because readers don't know what they are pointing to. See meta.stackexchange.com/questions/29518/…
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.