Search code examples
c++typecasting-operator

How do you implement mutual casts?


Say you have two struct types, one with int members and one with float.

struct i { 
    int a, b; 
    i(int a, int b): a(a), b(b) {}
};

struct f { 
    float a, b;
    f(float a, float b): a(a), b(b) {}
};

We want to define two cast operators, from i to f and conversely. If we try to do it by operator overloading

struct i { 
    int a, b; 
    i(int a, int b): a(a), b(b) {}
    operator f() const { return f(a, b); };
};

struct f { 
    float a, b;
    f(float a, float b): a(a), b(b) {}
    operator i() const { return i(a, b); };
};

we run in a problem of order of declaration, because i needs to know f and f needs to know i. Furthermore, the cast operators must be declared inside the classes. A forward declaration of f doesn't work.

Is there a solution ?


Solution

  • A forward declaration works fine:

    struct i;
    struct f;
    
    struct i
    {
        int a, b; 
        i(int a, int b): a(a), b(b) {}
        operator f() const;
    };
    
    struct f
    {
        float a, b;
        f(float a, float b): a(a), b(b) {}
        explicit operator i() const;
    };
    
    i::operator f() const { return f(a, b); }
    f::operator i() const { return i(a, b); }