c++ - 使用什么架构来暗示一个类中的 2 种行为?

标签 c++ architecture

我正在尝试创建一个同时代表两种不同行为的类。像下面这样:

class IMouse {
public:
    virtual void Walk() const = 0;
};

class TSimpleMouse : public IMouse {
public:
    void Walk() const;
};

class IBat {
public:
    virtual void Fly() const = 0;
};

class TSimpleBat : public IBat {
public:
    void Fly() const;
};

template <class TMouse, class TBat>
class TSuperCreatureImpl {
public:
    void Do() const {
        Walk();
        Fly();
    }
};

typedef TSuperCreatureImpl<TSimpleMouse, TSimpleBat> TSimpleSuperCreature;

这对我来说很重要,因为我想制作不同的 typedef。看起来很简单。

但我也希望 Fly 和 Walk 方法具有参数(例如速度)。我应该如何修改架构才能有机会为不同的生物使用许多 typedef?

如果 Mouse 和 Bat 没有默认构造函数,如何更改架构?

非常感谢。

最佳答案

template <class TMouse, class TBat>
class TSuperCreature : public TMouse, public TBat
{
  public:
    void do() const {
        this->walk();
        this->fly();
    }
};

But I also would like methods Fly and Walk to have parameters (velocity, for example). How should I modify the architecture to have an opportunity to use many typedefs for different creatures? Thanks a lot.

你可以给函数默认参数...

virtual void Walk(double meters_per_second = 1.1) const = 0;

编辑

(from comment below) Imagine that we need 2 creatures: first one walks fast and flies slow, second one is the opposite. That means we have to write 2 typedefs. But I have no idea how to use velovity constants here. Which parts of architecture must have parameters?

一个选择是做这样的事情:

template <class TMouse, class TBat, int walk_speed, int fly_speed>
class TSuperCreature : public TMouse, public TBat
{
  public:
    void do() const {
        this->walk(walk_speed);
        this->fly(fly_speed);
    }
};

如果你想使用 double,它们不允许作为模板参数(至少在 C++03 中不允许),但作为 hack 你可以接受一对数字并除以它们在模板中,或者更恰本地说,您可以提供一个策略类....

template <class TMouse, class TBat, class Speeds>
class TSuperCreature : public TMouse, public TBat
{
  public:
    void do() const {
        this->walk(Speeds::walk_speed);
        this->fly(Speeds::fly_speed);
    }
};

struct Speeds__Fly_Fast__Walk_Slow   // yes I know double underscores are reserved - I don't care!
{
    static const double walk_speed = 0.5; // m/s
    static const double fly_speed = 10;
};

关于c++ - 使用什么架构来暗示一个类中的 2 种行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10951877/

相关文章:

c++ - 为armhf编译Crypto++进行交叉编译

c++ - 2 个头文件中的 2 个类

c++ - 不能向侧面动态施放

java - 接口(interface)是否会因为减少 Java 编译器或 Eclipse 中的依赖关系而影响性能?

c# - 如何让数据访问技术(Entity Framework)脱离表现层(ASP.NET MVC)?

c++ - 使用嵌套包含文件夹创建 C++ NuGet 包

c++ - 部分模板特化仅限于某些类型

php - 我们应该在 PHP 中命名函数吗?

design-patterns - ServiceBus 如何工作?

architecture - 对 ESB 作为点对点集成的解决方案感到困惑