c++ - C++ 中的流畅接口(interface)和继承

标签 c++ inheritance fluent-interface

我想构建一个具有一些通用功能和流畅接口(interface)的基(抽象)类(我们称它为 type::base),我面临的问题是返回类型所有这些方法

  class base {
    public:
       base();
       virtual ~base();

       base& with_foo();
       base& with_bar();
    protected:
       // whatever...
  };

现在我可以制作子类型,例如:

  class my_type : public base {
    public:
      myType();        
      // more methods...
  };

当像这样使用这些子类型时,问题就来了:

 my_type build_my_type()
 {
    return my_type().with_foo().with_bar();
 }

这不会编译,因为我们返回的是 base 而不是 my_type。

我知道我可以:

 my_type build_my_type()
 {
    my_type ret;
    ret.with_foo().with_bar();

    return ret;
 }

但我一直在想如何实现它,但我没有找到任何有效的想法,有什么建议吗?

最佳答案

这个“丢失类型”的问题可以用模板来解决——但它相当复杂。

例如。

class Pizza
{
  string topping;
public:
  virtual double price() const;
};

template <class T, class Base>
class FluentPizza : public Base
{
  T* withAnchovies() { ... some implementation ... };
};

class RectPizza : public FluentPizza<RectPizza, Pizza>
{
  double price() const { return length*width; :) }
};

class SquarePizza : public FluentPizza<SquarePizza, RectPizza>
{
   ... something else ...
};

然后你可以写

SquarePizza* p=(new SquarePizza)->withAnchovies();

模式是,而不是

class T : public B

你写

class T : public Fluent<T, B>

另一种方法可能不是在对象上使用流畅的接口(interface),而是在指针上:

class Pizza { ... };
class RectPizza { ... };
class SquarePizza { ... whatever you might imagine ... };

template <class T>
class FluentPizzaPtr
{
  T* pizza;
public:
  FluentPizzaPtr withAnchovies() {
    pizza->addAnchovies(); // a nonfluent method
    return *this;
  }
};

像这样使用:

FluentPizzaPtr<SquarePizza> squarePizzaFactory() { ... }

FluentPizzaPtr<SquarePizza> myPizza=squarePizzaFactory().withAnchovies();

关于c++ - C++ 中的流畅接口(interface)和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1041342/

相关文章:

c++ - C++中虚表的结构是怎样的?

c++ - 我是否需要 SE_SHUTDOWN_NAME 权限才能注销用户?

c++ - 派生类实例共享同一个基类实例

c# - DSL/流畅接口(interface)的意义何在

c# - 在 C# 3 中编写流畅接口(interface)的技巧

c++ - "I' m busy please wait"窗口 - 没有按钮

C++ 匿名 union 重新声明错误

java - 如何实现具有不同参数数量的抽象方法

C# 返回对象作为基继承接口(interface)

database - EF 代码优先 : Many-to-many and one-to-many