是否可以编写返回派生类型的流畅的链宁方法?考虑以下两个类:
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 服务器。我有一个 RestConnection
类,方法是 withUrl
,一个 PostableRest
类,方法是 withParam
和 doPost
和一个带有 doGet
的 GettableRest
类。我怀疑这是不可能的,并且可能会尝试将一堆虚拟方法塞进 RestConnection
但我讨厌在有多个 withParam
重载时这样做,其中一些不包含在 GET 参数列表中是有意义的。
提前致谢!
最佳答案
我想你可以利用 CRTP在这里,类似于下面的内容,其中派生类告诉基类它是什么类型:
class Base
{
// Abstract/virtual interface here.
};
template <class Derived>
class Base_T : public Base
{
private:
std::string mFoo;
public:
Derived& withFoo(std::string foo) {
mFoo = foo;
return *static_cast<Derived*>(this);
}
};
class Derived : public Base_T<Derived> {
private:
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;
}
};
关于c++ - 方法链接与多态性 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18384701/