Compiling Java Generics with Wildcards to C++ Templates

前端 未结 3 1781
旧巷少年郎
旧巷少年郎 2021-02-10 04:26

I am trying to build a Java to C++ trans-compiler (i.e. Java code goes in, semantically \"equivalent\" (more or less) C++ code comes out).

Not considering garbage collec

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-10 04:52

    An approach you haven't discussed is to handle generic wildcards with a wrapper class template. So, when you see Collection, you replace it with an instantiation of your template that exposes a read-only[*] interface like Collection but wraps an instance of Collection. Then you do your type erasure in this wrapper (and others like it), which means the resulting C++ is reasonably nice to handle.

    Your chainsaw reinterpret_cast is not guaranteed to work. For instance if there's multiple inheritance in String, then it's not even possible in general to type-pun a String* as an Object*, because the conversion from String* to Object* might involve applying an offset to the address (more than that, with virtual base classes)[**]. I expect you'll use multiple inheritance in your C++-from-Java code, for interfaces. OK, so they'll have no data members, but they will have virtual functions, and C++ makes no special allowance for what you want. I think with standard-layout classes you could probably reinterpret the pointers themselves, but (a) that's too strong a condition for you, and (b) it still doesn't mean you can reinterpret the collection.

    [*] Or whatever. I forget the details of how the wildcards work in Java, but whatever's supposed to happen when you try to add a T to a List, and the T turns out not to be an instance of ?, do that :-) The tricky part is auto-generating the wrapper for any given generic class or interface.

    [**] And because strict aliasing forbids it.

提交回复
热议问题