我想是這樣的:C++子類參數化類,並使用子類作爲一個專業化
class TestParent<class T>
{
T* some();
}
class TestChild : public TestParent<TestChild>
{};
這可能嗎?
謝謝。
我想是這樣的:C++子類參數化類,並使用子類作爲一個專業化
class TestParent<class T>
{
T* some();
}
class TestChild : public TestParent<TestChild>
{};
這可能嗎?
謝謝。
這是可能的,但只有當您定義some
的實現,否則您將面臨編譯錯誤。您可能還需要添加一個受保護的構造函數,以便您的基類不能在您的頭範圍內定義之外創建和使用。
template<typename T>
class TestParent{
public:
T* some() { return new T(); }
//this is suggested
protected:
TestParent(){}
};
class TestChild : public TestParent<TestChild>{}
這在curiously recuring template pattern使用和policy-based design其他技術通過Alexandrescu的的book流行起來。
+1爲鏈接,非常有用 – Gerard 2014-05-08 11:04:39
絕對!這種技術通常用於高級技術,如the Curiously Recurring Template Pattern或實施static polymorphism。如果您進行高級C++編程,您會看到很多。
當然你的意思是`template class TestParent`? –
2011-02-11 22:48:32