c++casting

C++ Setup own cast rules for template classes/structures


is it possible to implement your own cast rules and to make the compiler give a warning about it rather than an error?

I'm currently working with SFML (doesn't really matter if you don't know it) and it has a simple Vector2 structure like this:

template <typename T>
struct Vector2 {
    Vector2<T>(T,T);
    T x,y;
}

Now I'm using this quite often and would like to setup a custom cast rule for this structure, since I can't modify the source code. I currently have a function that needs a Vector2<int>, but a function I use returns a Vector2<unsigned int> and the compiler doesn't seem to be able to cast the one into the other which is a bit weird.

I know I can use the casts (and static_cast works), but it seems a bit too elaborate for a a simple conversion like this, and a bit stupid that I can't test my program because of this. So what I'm probably searching for are compiler commands that can setup such cast rules.


Solution

  • There are two ways to do this (both ways require you to modify the definition of Vector2). You can add a non-explicit constructor that performs the conversion:

    template <typename T>
    struct Vector2 {
        template<typename U>
        Vector2(Vector2<U> const& u) : x(u.x), y(u.y){}
        Vector2(T x,T y) : x(x), y(y) {}
        T x,y;
    };
    

    or you can add a non-explicit type-cast operator:

    template <typename T>
    struct Vector2 {
        template<typename U>
        operator Vector2<U>(){
            return Vector2<U>(x,y);
        }
        Vector2(T x,T y) : x(x), y(y) {}
        T x,y;
    };