gpt4 book ai didi

C++ CRTP 类层次结构

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:48:08 24 4
gpt4 key购买 nike

来自 Wikipedia :

// The Curiously Recurring Template Pattern (CRTP)
template <typename T>
struct base
{
// ...
};
struct derived : base<derived>
{
// ...
};

现在如果我想要derived_from_derived,我可以写:

// The Curiously Recurring Template Pattern (CRTP)
template <typename T>
struct base
{
// ...
};
template <typename T>
struct derived : base<T>
{
// ...
};
struct derived_from_derived : derived <derived_from_derived>
{
// ...
};

现在假设我只想要一个derived 对象。这不起作用:

derived<derived> obj;

derived 是否必须是抽象的,或者有没有办法实例化它?

最佳答案

我自己的答案是这样的:

struct base
{
template <typename T>
struct type
{
// ...
};
};
struct derived
{
template <typename T=derived>
struct type : base::type<T>
{
// ...
};
}
struct derived_from_derived
{
template <typename T=derived_from_derived >
struct type : derived::type<T>
{
// ...
};
};

现在我可以拥有一个derived::type<> obj .此外,参数化继承有效(例如装饰器模式):

template <typename whatever>
struct derived_from_whatever
{
template <typename T=derived_from_whatever>
struct type : whatever::type<T>
{
// ...
};
};

derived_from_whatever<derived_from_derived>::type<> obj_whatever;

关于C++ CRTP 类层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7873989/

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