user5739133
user5739133

Reputation:

How to Dynamically Cast a Template Class

I'm trying to write an API around the following class template:

template <class A, class B>
class MyClass {
    public:
        A foo;
        B bar;
        MyClass();
        MyClass(A in1, B in2) {
            foo = in1; bar = in2;
        }
        void operator = (MyClass<A, B> in) {
            foo = in.foo; bar = in.bar;
        }
};

As a part of this API, I would like implementers to be able to dynamically cast between different types of MyClass. In order to accomplish this, I have written the following function:

template<class A, class B, class C, class D>
MyClass<C, D> operator MyClass<C, D> (MyClass<A, B> in) {
    MyClass<C, D> out((C)in.foo, (D)in.bar);
    return out;
}

This code compiled without errors.


My Question:
Assuming that both C operator C (A) and D operator D (B) are defined for any given implementation of the above function, will this crazy looking function be sufficient to allow implementers to dynamically cast between types of MyClass, (via (MyClass<C, D>)MyClass<A, B>) or have I completely lost it?



Example Implementation:

/*
  * --- INCLUDE ABOVE CLASS DEFINITION HERE ---
*/

#include <iostream>
#include <string>

int main() {
    MyClass<int, char> foo(42, 'q');
    MyClass<double, std::string> bar;

    bar = (MyClass<double, std::string>) foo;
}

Upvotes: 5

Views: 650

Answers (1)

Answer: YES.

But you must provide ALL VARIANTS OF C operator C (A) and D operator D (B), and you need a copy constructor like this:

class MyClass
{
public:
    A foo;
    B bar;
    MyClass(MyClass &cpy)// copy constructor
   {
       foo = cpy.foo;
       bar = cpy.bar;
   }
   MyClass(A in1, B in2)
   {
       foo = in1; bar = in2;
   }
};

Copy constructor is required in order to work:

    return out;

in MyClass(A in1, B in2) method

Upvotes: 1

Related Questions