user75832
user75832

Reputation:

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

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

Upvotes: 2

Views: 10940

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361482

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

Upvotes: 5

Erik
Erik

Reputation: 91270

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

Upvotes: 0

Related Questions