2011-02-15 48 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> { 
};