C++ - 将新运算符与模板提供的类型名一起使用
我有一个类模板,可以传递类或类指针。
/* 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 类型或其他解决方案中删除 * 吗?
谢谢 本
I have a class template which can be passed a Class or Class pointer.
/* 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;
}
};
Compilation fails with the following error:
cannot convert 'Class**' to 'Class*' in initialization
I think this is because T is already a pointer new T()
thinks i want to allocate a pointer to a pointer. e.g.
OtherClass * new_obj = OtherClass*new();
Is there some way i can strip the * from the T type or another solution?
Thanks
Ben
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当然可以。
使用这个:(它只删除一级指针,即它使 T* -> T 和 T** -> T* 等)
然后,
如果你想使
T***->
T
即删除所有*
,然后用以下内容替换上面的专业化:Of course, you can.
Use this: (it removes just one degree of pointerness, i.e it makes T* -> T, and T** -> T*, etc)
Then,
If you want to make
T***
->T
i.e remove all*
, then replace the above specialization with this:或者使用它来删除类型中的任何间接级别。
Or use this, to remove any level of indirection from the type.