I have an auto pointer class and in the constructor I am passing in a pointer. I want to be able to separate new from new[] in the constructor so that I can properly call delete or delete[] in the destructor. Can this be done through template specialization? I don't want to have to pass in a boolean in the constructor.
template <typename T>
class MyAutoPtr
{
public:
MyAutoPtr(T* aPtr);
};
// in use:
MyAutoPtr<int> ptr(new int);
MyAutoPtr<int> ptr2(new int[10]);
This is called template specialization. Template allows us to define generic classes and generic functions and thus provide support for generic programming. Generic programming is an approach where generic data types are used as parameters in algorithms so that they work for variety of suitable data types.
Explicit (full) specializationAllows customizing the template code for a given set of template arguments.
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.
Template non-type arguments in C++It is also possible to use non-type arguments (basic/derived data types) i.e., in addition to the type argument T, it can also use other arguments such as strings, function names, constant expressions, and built-in data types.
Unfortunately, no. Both return the same type, T*
. Consider using builder functions that call an appropriate overloaded constructor:
template <typename T>
class MyAutoPtr
{
public:
MyAutoPtr(T* aPtr, bool array = false);
};
template <typename T>
MyAutoPtr<T> make_ptr() {
return MyAutoPtr<T>(new T(), false);
}
template <typename T>
MyAutoPtr<T> make_ptr(size_t size) {
return MyAutoPtr<T>(new T[size], true);
}
Now you can instantiate objects as follows:
MyAutoPtr<int> ptr = make_ptr<int>();
MyAutoPtr<int> ptr2 = make_ptr<int>(10);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With