bla*_*ter 7 c++ inheritance fluent-interface
我想type::base用一些常用的功能和流畅的接口构建一个基类(抽象)类(让我们称它),我面临的问题是所有这些方法的返回类型
class base {
public:
base();
virtual ~base();
base& with_foo();
base& with_bar();
protected:
// whatever...
};
Run Code Online (Sandbox Code Playgroud)
现在我可以制作子类型,例如:
class my_type : public base {
public:
myType();
// more methods...
};
Run Code Online (Sandbox Code Playgroud)
使用这样的子类型时出现问题:
my_type build_my_type()
{
return my_type().with_foo().with_bar();
}
Run Code Online (Sandbox Code Playgroud)
这将无法编译,因为我们正在返回base而不是my_type.
我知道我可以:
my_type build_my_type()
{
my_type ret;
ret.with_foo().with_bar();
return ret;
}
Run Code Online (Sandbox Code Playgroud)
但我在想如何实现它,我没有找到任何有效的想法,一些建议?
您应该返回引用/指针,并且您不需要保留类型信息.
class base {
public:
base();
virtual ~base();
base &with_foo();
base &with_bar();
protected:
// whatever...
};
class my_type : public base {
public:
my_type();
// more methods...
};
base *build_my_type()
{
return &new my_type()->with_foo().with_bar();
}
Run Code Online (Sandbox Code Playgroud)
你已经有了一个虚拟的析构函数.大概你有其他虚拟功能.通过基类型和在那里声明的虚函数访问所有内容.
这个“丢失类型”的问题可以用模板来解决——但它相当复杂。
例如。
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 ...
};
Run Code Online (Sandbox Code Playgroud)
然后你可以写
SquarePizza* p=(new SquarePizza)->withAnchovies();
Run Code Online (Sandbox Code Playgroud)
模式是,而不是
class T : public B
Run Code Online (Sandbox Code Playgroud)
你写
class T : public Fluent<T, B>
Run Code Online (Sandbox Code Playgroud)
另一种方法可能是不在对象上使用流畅的接口,而是在指针上使用:
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;
}
};
Run Code Online (Sandbox Code Playgroud)
像这样使用:
FluentPizzaPtr<SquarePizza> squarePizzaFactory() { ... }
FluentPizzaPtr<SquarePizza> myPizza=squarePizzaFactory().withAnchovies();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2109 次 |
| 最近记录: |