Question
I have a series of ~10 template classes A, B, C, D, ...
I want to enable conversions from a class to previous classes in the series
Although @hlt's approach will do what you ask, without knowing more about the context, I'm wary about implementing the conversion in A
. In the cases I can think of, A
shouldn't be aware of B
, C
or D
, so I'll suggest a different implementation.
You can create a variant of your test 3, where you implement one conversion operator per class, but where you also inherit a templated indirect conversion operator, like so:
#include
template
struct indirect_conversion {
template >>
operator T() {
return static_cast(this)->operator T2();
}
};
struct A {};
struct B : indirect_conversion {
operator A();
};
struct C : indirect_conversion {
operator B();
};
struct D : indirect_conversion {
operator C();
};
A a = D();