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;
}