我有一个类模板可以通过类或类指针。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