假設我有這個類:
template <class T>
class Test
{
Test(T* x);
const T* const t。
int i{0};
};
我希望t總是被初始化為x:
template <class T> Test< T> 。 :Test(T* x) : t{x} {}
而且我有兩個專業:
template <> Test<Foo> ::Test(Foo* x) : t{x} { i = 1; }
template <> Test<Bar>::Test(Bar* x) : t{x}。{ i = 2; }
接下來,我將用一些其他的東西來擴展這個類,而第一個(模板化的)建構式不僅僅是設定t,還做了很多事情。
所有我想為T = Foo和T = Bar做的事情。
有什么方法可以讓我從專門的建構式中呼叫模板化的建構式嗎?
//this does not work, since it will create a delegation cycle。
template <> Test<Foo>::Test(Foo* x) : Test(x) { i = 1; }
template <> Test<Bar>::Test(Bar* x) : Test(x) { i = 2; }
uj5u.com熱心網友回復:
你可以使用轉授建構式來實作。 你可以創建一個私有的建構式,它接收t的指標,以及i的int,然后你可以用它來設定x和i,并運行所有的通用代碼。 這看起來就像
template <class T>
class Test
{
public:
Test(T* x) : Test(x, 0) { /*code for default case, runs after delegate*/ }
private:
Test(T* t, int i) : t(t), i(i) { /*code to run for everything */ }
const T* const t。
int i;
};
template <> Test<Foo>::Test(Foo* x)。Test(x, 1) { /*code only for Foo, runs after delegate*/ }
template <> Test<Foo>::Test(Bar* x)。
uj5u.com熱心網友回復:
你想過繼承問題嗎?我想到的第一件事是做一個Test類,它是從基類派生出來的,它將有所有你想讓foo和bar都一樣的東西來處理。所以你可以在派生類(Test)中呼叫基類的建構式,然后只為Foo和bar做事情。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/314103.html
標籤:
下一篇:使用make命令編譯C 11
