开发者

C++ - Using the new operator with a template provided typename

开发者 https://www.devze.com 2023-02-11 09:50 出处:网络
I have a class template which can be passed a Class or Class pointer. /* Template specialization hack to determine if type is a pointer */

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 &l开发者_如何学JAVAt;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


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

Of course, you can.

Use this: (it removes just one degree of pointerness, i.e it makes T* -> T, and T** -> T*, etc)

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

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

Then,

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

If you want to make T*** -> T i.e remove all *, then replace the above specialization with this:

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


Or use this, to remove any level of indirection from the type.

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> {
};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号