Search code examples
c++templatesrust

Is there a way to auto generate Rust code from C++ code which uses templates?


I am a beginner in rust and was looking into bindgen, cxx and autocxx etc for auto generation of Rust code C/C++.

However, I am stuck at a point where the pre-written source heavily uses generics i.e C++ templates. I am unable to share a snippet because I'm not supposed to, :-) So I am looking for any pointers that would help me to generate correct rust code from a C++ source that uses C++ template.

So far I have tried the cxx crate but without significant progress.

Any help will be greatly appreciated.

Thank you


Solution

  • C++ templates and Rust Generics are somewhat similar in both syntax and in the kind of problems they solve, but the details are very different.

    Generics are type checked at declaration time. C++ templates are not.

    A program that tries to take C++ templates and generate equivalent Generics has to invent type annotations to allow the Generic to guarantee correctness of the code.

    I doubt that is solvable in general. The validity of the C++ template depends on C++ name lookup rules, and code translated from C++ to idiomatic Rust isn't going to have the same name lookup rules.

    Basically, short of writing a C++ interpreter in Rust, you aren't going to be able to do this 100% perfectly, and failures are going to be difficult to understand, and often won't even generate a compile time error!

    In comparison, C++ non-template code can be mechanically converted to a common C-like meaning that Rust is also easily able to express.

    C++ programmers use the rather insane power of the template language to do Turing-complete compile time computations to select how templates are instantiated and used. A translation of this to another language is probably not a good idea even if possible: Rust has its own mechanisms to solve those problems that aren't quite as crazy.

    Beware the Turing Tar Pit.