是否可以编写返回派生类型的流利的链接方法?考虑以下两个类:
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先指定派生的 s。问题是我的构建器方法(doOutput在上面的示例中)需要单独声明。
Derived d;
d.withBar("this is a bar")
.withFoo("this is my foo");
d.doOutput();
我的问题是是否有某种方法withFoo可以返回未知的派生类型,以便Base可以与多个派生类无缝使用(毕竟*this 是a Derived,尽管Base(正确地)不知道这一事实)。
举一个更具体的例子,我正在编写一些类来访问 REST 服务器。我有一个RestConnection带有方法的类withUrl,一个PostableRest带有方法withParam和的类doPost,以及一个GettableRest带有doGet. 我怀疑这是不可能的,并且可能会尝试将一堆虚拟方法塞入RestConnection其中,但是当有多个withParams 重载时,我讨厌这样做,其中一些包含在 GET 参数列表中没有意义。
提前致谢!