Search code examples
c++type-conversionlibraries

In C++, what is the best way to do conversions of similar classes between libraries?


I happen to be working on a project that uses the glm and Box2D libraries. Both of these include implementations of, for example, a 2D vector. Sometimes, I'll need to convert values from one library's format to another. I can't just write the appropriate constructors in the classes because that would involve modification of the library source code, which is a bad idea for many reasons.

Now, the obvious solution is just to write some utility functions that convert one to another, eg. convertVec2(). This would work. However, it's a bit clunky and verbose, and I can't help but wonder if there's some cleverer way of doing it, possibly using some cunning use of obscure language functionality.

Is there a better way to solve the problem? Or should I just do the boring and straightforward thing?


Solution

  • the obvious solution is just to write some utility functions that convert one to another

    should I just do the boring and straightforward thing?

    Yes, this is a decent approach.

    Note that in special case of the types being layout compatible, you can simply reinterpret a pointer to one as being a pointer to the other type.

    In short, types are layout compatible if they are either the same type, or both are standard layout classes and all members of each class are layout compatible with the corresponding member of the other class. For example, following classes are layout compatible:

    struct Vec2D {
        float x, y;
    };
    
    
    struct Point {
        float X, Y;
    };
    

    Since C++20 you can test that with the type trait std::is_layout_compatible.