我有一個類模板可以通過類或類指針。C++ - 使用提供模板的新運營商typename
/* Template specialization hack to determine if type is a pointer */
struct type_true { };
struct type_false { };
template <class PRT>
class is_pointer : public type_false {
};
template <class PRT>
class is_pointer <PRT * > : public type_true {
};
template <typename T>
class MyClass {
//Return an new instance allocated on stack
T new_instance(type_false n_ptr) {
T new_obj;
//Init stuff
return new_obj;
}
//Return an new instance allocated on heap
T new_instance(type_true is_ptr) {
T new_obj = new T();
//Init stuff
return new_obj;
}
};
編譯失敗,出現以下錯誤:
cannot convert 'Class**' to 'Class*' in initialization
我想這是因爲T是已經new T()
認爲我想一個指針分配給一個指針的指針。例如
OtherClass * new_obj = OtherClass*new();
有什麼方法可以從T型或其他解決方案中剝離*嗎?
感謝 本
您遇到了更深層次的問題。 「返回在堆棧上分配的新實例」不會。首先,C++沒有堆棧的概念,你創建的是一個自動變量。然後你不返回它,你會返回一個副本(這是很好的,因爲自動變量的生命週期在任何事情都可以使用之前結束)。 – 2011-02-15 18:52:30