2011-02-15 45 views
2

我有一个类模板可以通过类指针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型或其他解决方案中剥离*吗?

感谢 本

+0

您遇到了更深层次的问题。 “返回在堆栈上分配的新实例”不会。首先,C++没有堆栈的概念,你创建的是一个自动变量。然后你不返回它,你会返回一个副本(这是很好的,因为自动变量的生命周期在任何事情都可以使用之前结束)。 – 2011-02-15 18:52:30

回答

6

Is there some way i can strip the * from the T type or another solution?

当然,你可以。

使用此:(它消除只是一个程度pointerness的,也就是说,它使得T * - > T和T ** - > T *等)

template<typename T> 
struct remove_pointer 
{ 
    typedef T type; 
}; 

template<typename T> 
struct remove_pointer<T*> 
{ 
    typedef T type; 
}; 

然后,

typedef typename remove_pointer<T>::type type; 
T new_obj = new type(); 

如果你想T*** - >T即删除所有*,然后更换这个上面专业化:

template<typename T> 
struct remove_pointer<T*> 
{ 
    typedef typename remove_pointer<T>::type type; 
}; 
0

或者使用它来从类型中删除任何间接级别。

template<typename T> struct stripptr { 
    typedef T thetype; 
}; 

template<typename T> struct stripptr<T *> { 
    typedef T thetype; 
}; 


template <typename T> struct MyClass { 
    static T create() { 
     T new_obj; 
     return new_obj; 
    } 
}; 

template <typename T> struct MyClass<T *> : MyClass<T> { 
};