是否可以編寫返回派生類型的流暢chanining方法?考慮下面兩個類:方法鏈多態C++
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
,和GettableRest
類與doGet
。我懷疑這是不可能的,並且可能會嘗試將一堆虛擬方法填入RestConnection
,但是我討厭這樣做,當有多個withParam
s被重載時,其中一些沒有意義包含在GET參數列表中。
在此先感謝!
您可以爲Base指定一個模板參數,並且Derived從Base繼承時將其自身作爲參數傳遞。現在Base可以返回對這個模板參數的引用。 –
您可能感興趣的裝飾圖案。 – Jarod42
你是否還需要從'Base'到各種派生類的運行時多態?另外請注意,一般來說,受保護的屬性(不是方法)是一種強烈的設計氣味,因爲它們容易違反不變量。 –