David Doria
David Doria

Reputation: 10273

Construct a type that changes the base class of a mixin

I would like to be able to change the type of the inner-most type of a mixin. A sketch is shown below:

struct PointTypeA {
    double x,y;
};

struct PointTypeB {
    double x,y,z;
};

template<class Base>
class MyMixin1 : public Base {
public:
    double someProperty;
};

template<class Base>
class MyMixin2 : public Base {
public:
    double someProperty;
};

// how do we automatically construct MyMixin2<MyMixin1<TNewInside> > from MyMixin2<MyMixin1<PointTypeA> >
// template <typename T, typename TNewInside>
// ChangedType ChangeInsideType(T object) {
//     return ChangedType(object);
// }

int main() {
    typedef MyMixin2<MyMixin1<PointTypeA> > Mixed12A;
    Mixed12A mixed12A;

    //MyMixin2<MyMixin1<PointTypeB> > mixed12B = ChangeInsideType<Mixed12AType, PointTypeB>(mixed12A);
    return 0;
}

Is something like this possible?

Upvotes: 1

Views: 78

Answers (1)

TartanLlama
TartanLlama

Reputation: 65580

Replacing the inner template parameter can be done using this:

template <class ToReplace, class With>
struct replace_inner {
    using type = With;  
};

template <template <class> class Outer, class Inner, class With>
struct replace_inner<Outer<Inner>, With> {
    using type = Outer<typename replace_inner<Inner, With>::type>;
};

template <class ToReplace, class With>
using replace_inner_t = typename replace_inner<ToReplace,With>::type;

We use it like so:

using replaced = replace_inner_t<MyMixin1<MyMixin2<PointTypeA>>, PointTypeB>;
static_assert(
    std::is_same<replaced, MyMixin1<MyMixin2<PointTypeB>>>::value, "wat"
);

Then you just need to write the converting constructors between the point types and mixins with different template parameters.

Upvotes: 1

Related Questions