C++ 构造更改mixin基类的类型

C++ 构造更改mixin基类的类型,c++,templates,C++,Templates,我想能够改变最里面的混音类型。草图如下所示: 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

我想能够改变最里面的混音类型。草图如下所示:

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;
}
struct PointTypeA{
双x,y;
};
结构点类型B{
双x,y,z;
};
模板
类MyMixin1:公共基{
公众:
双重属性;
};
模板
类MyMixin2:公共基{
公众:
双重属性;
};
//我们如何从MyMixin2自动构造MyMixin2
//模板
//ChangedType ChangeInsideType(T对象){
//返回ChangedType(对象);
// }
int main(){
类型def MyMixin2 Mixed12A;
混合12a混合12a;
//MyMixin2 mixed12B=ChangeInsideType(mixed12A);
返回0;
}

可以这样做吗?

可以使用以下方法替换内部模板参数:

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;
模板
结构替换内部{
使用type=With;
};
模板
结构替换内部{
使用类型=外部;
};
模板
使用replace\u inner\u t=typename replace\u inner::type;
我们这样使用它:

using replaced = replace_inner_t<MyMixin1<MyMixin2<PointTypeA>>, PointTypeB>;
static_assert(
    std::is_same<replaced, MyMixin1<MyMixin2<PointTypeB>>>::value, "wat"
);
使用替换=替换内部\u t;
静态断言(
std::值“wat”是否相同
);

然后,您只需编写点类型和具有不同模板参数的mixin之间的转换构造函数。

太棒了,谢谢。现在我不得不取消我的周末计划来研究到底发生了什么:)@DavidDoria本质上它会沿着外部类型递归,直到用完为止,然后用您指定的类型替换内部类型。我想我快接近了。对于3个代码块:1)这是递归的基本情况,递归在到达非模板类时切换内部类型。2) 这是replace_internal的部分专用版本,其中第一个模板参数是一个模板参数(我们的mixin将在此处显示为Outer)。在这个“使用类型”的内部,我们有一个递归,在内部本身上调用replace_inner。3) 一种方便的打字机。我的困惑在于专业化-当原来的replace_inner只有2个参数时,它怎么可能有3个参数?@DavidDoria完全正确!专门化可以比主模板(您称之为“基本情况”)拥有更多的模板参数,只要它们可以从专门化参数(即
)中推导出来。那么它如何知道我们所说的外部参数是什么呢?在“顶级”调用中,外部可以是MyMixin1,而内部可以是MyMixin2,或者外部可以是MyMixin1,内部可以是PointTypeA——两者似乎都符合外部模式?