gpt4 book ai didi

c++ - 构造一个改变混合基类的类型

转载 作者:行者123 更新时间:2023-11-30 05:31:55 25 4
gpt4 key购买 nike

我希望能够更改混入的最内层类型。示意图如下:

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

这样的事情可能吗?

最佳答案

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

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;

我们这样使用它:

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

然后你只需要用不同的模板参数编写点类型和mixins之间的转换构造函数。

关于c++ - 构造一个改变混合基类的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35364863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com