Search code examples
c++box2dimplicit-conversionglm-math

Automatic converstion without access to the classes


I'm using two kinds of vectors (float x,y structs) in my engine.

One us the openGL vector, glm::vec2. We use this basically everywhere.

Recently we added collision with a library called Box2d. This uses b2vec types everywhere.

I want some way to automatically convert from glm::vec2 to b2vec whenever I pass it into a box2d function, instead of doing it manually constantly.

Problem is: At this time I don't have the access to the glm::vec2 or b2vec classes directly. I can't add the conversion constructors to them.

Do I have any other options?


Solution

  • Unfortunately, automatic conversion operators must be defined as a non-static member function of the class being converted (glm::vec2 in your case).

    struct A {};
    
    struct B {
        operator A();
    };
    

    Or, switched around, as a constructor for class A.

    struct A {
        A(const B&);
    };
    

    The only other option is to make a non-member converter function.

    struct A {};
    struct B {};
    
    A convert_to_A(const B&);