c++ - 如何使派生类在 CRTP 中的基类上模板化

标签 c++ templates traits crtp

比方说,我有两个引擎类别(基于燃料类型,例如天然气或电力)

template<class Derived>
class ElectricEngine {};

template <typename Derived>
class GasEngine {};

现在说我要制作CarEnginePlaneEngine,每个可以选择上面的基类之一。我还需要做 CRTP(静态多态性)。因此,执行此操作的直接方法如下:

class ElectricCarEngine : public ElectricEngine<ElectricCarEngine> {};
class GasCarEngine : public GasEngine<GasCarEngine> {};

class ElectricPlaneEngine : public ElectricEngine<ElectricPlaneEngine> {};
class GasPlaneEngine : public GasEngine<GasPlaneEngine> {};

上面的代码有效,但是它有很多冗余代码,因为我对每个 CarEngine 类型(即 ElectricCarEngineGasCarEngine)的方法是相同的。 ElectricPlaneEngineGasPlaneEngine 也是如此。

假设像下面这样编译:

template <typename Base>
class CarEngineInterface : public Base<CarEngineInterface<Base> > {};

然后我们可以通过简单的 typedfs 重用这个类来创建任何 CarEngine 类型。 例如:

typedef CarEngineInterface<ElectricCarEngine> ElectricCarEngine;
typedef CarEngineInterface<GasCarEngine> ElectricCarEngine;

然而,由于循环依赖,这失败了。我怎样才能达到类似的效果?

是否有一些特质魔法可以解决这个问题? (就像用于从 CRTP 中的基类引用派生类 typedef 的那些)

我在使用 C++99,但我可以使用 Boost。我也是 C++ 模板的菜鸟。

如果我需要澄清任何事情,请告诉我。

创意链接:https://ideone.com/uMylVY

最佳答案

模板也可以接受模板作为参数,所以我认为这将用于:

template< class Engine > struct ElectricFueled { };
template< class Engine > struct GasFueled { };

template< template<class> class Fueled > struct CarEngine   : Fueled<CarEngine<Fueled> >   { };
template< template<class> class Fueled > struct PlaneEngine : Fueled<PlaneEngine<Fueled> > { };

CarEngine<ElectricFueled> myTeslaEngine;
PlaneEngine<GasFueled>    myMooneyEngine;

这可能是在结构语法方面分解它的最简单方法,但它只是一种方法。尝试多种变体,看看什么能让以后的生活变得更轻松。

关于c++ - 如何使派生类在 CRTP 中的基类上模板化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22875658/

相关文章:

c++ - 在 C++ 中从彩色图像创建蒙版(叠加彩色图像蒙版)

rust - 使用不同的实现返回 Trait 实现

c++ - 转发与不转发传递给包装器的函数

c++ - 缺少模板参数错误

c++ - 让函数指针模板参数接受右值引用是否合法?

traits - 特质是否仅适用于对象?

rust - 我如何使用特征方法的默认实现而不是类型的自定义实现?

c++ - 了解 '&' 运算符

c++ - Quicksort 无法一致地对 100 000 个整数的数据集进行排序

c++ - 如何在 C++ 中实现谷歌测试分片?