是否可能编写流畅的链式方法并返回派生类型?考虑以下两个类:
class Base {
protected:
std::string mFoo;
public:
Base& withFoo(std::string foo) {
mFoo = foo;
return *this;
}
};
class Derived : public Base {
protected:
std::string mBar;
public:
Derived& withBar(std::string bar) {
mBar = bar;
return *this;
}
void doOutput() {
std::cout << "Foo is " <<
mFoo << ". Bar is " <<
mBar << "." << std::endl;
}
};
我希望能创建我的对象并像下面这样使用它:
Derived d;
d.withFoo("foo").withBar("bar").doOutput();
当然,这种方法会失败,因为
withFoo
返回一个Base
。由于我所有的with
方法都只是设置成员变量,所以我可以先指定派生的with
。问题在于我的构建器方法(如上面的doOutput
)将需要成为一个单独的语句。Derived d;
d.withBar("this is a bar")
.withFoo("this is my foo");
d.doOutput();
我的问题是,是否有一种方法让
withFoo
返回一个未知的派生类型,以便Base
可以无缝地与多个派生类一起使用(毕竟* this
是一个Derived
,虽然Base
(正确地)不知道这件事)。举个更具体的例子,我正在编写一些访问REST服务器的类。我有一个带有
withUrl
方法的RestConnection
类,一个带有withParam
和doPost
方法的PostableRest
类,以及一个带有doGet
方法的GettableRest
类。 我怀疑这是不可能的,可能会尝试将一堆虚拟方法塞进RestConnection
中,但当有多个重载的withParam
时,其中一些在GET参数列表中包含没有意义,所以我不想这么做。提前致谢!
Base
到各种派生类的运行时多态性?另请注意,通常来说,受保护的属性(而不是方法)是一种强烈的设计气味,因为它们容易违反不变量。 - Mark B