Chained conversion between classes without public inheritances

后端 未结 2 1956
挽巷
挽巷 2021-01-16 12:54

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

2条回答
  •  一向
    一向 (楼主)
    2021-01-16 13:35

    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();
    

提交回复
热议问题