Optional parameter for reference to pointer?
-
21-09-2019 - |
Question
How do I declare the second parameter as optional?
template <typename T>
inline void Delete (T *&MemoryToFree,
T *&MemoryToFree2 = ){
delete MemoryToFree;
MemoryToFree = NULL;
delete MemoryToFree2;
MemoryToFree2 = NULL;
}
I tried several things after the = operator, like NULL, (T*)NULL etc. Can this be done?
The only way the compiler let me do it was using an overload...
template <typename T, typename T2>
inline void Delete (T *&MemoryToFree, T2 *&MemoryToFree2){
delete MemoryToFree;
MemoryToFree = NULL;
delete MemoryToFree2;
MemoryToFree2 = NULL;
}
Solution
You could just overload the function
template <typename T>
inline void Delete (T *&MemoryToFree){
delete MemoryToFree;
MemoryToFree = NULL;
}
template <typename T, typename T2>
inline void Delete (T *&MemoryToFree, T2 *&MemoryToFree2){
delete MemoryToFree;
MemoryToFree = NULL;
delete MemoryToFree2;
MemoryToFree2 = NULL;
}
OTHER TIPS
You could always write a simple "on-demand static lvalue generator" and use it as the default value for your parameter
template <typename T> inline T& get_lvalue() {
static T t;
return t;
}
In your code
template <typename T>
inline void Delete(T *&MemoryToFree, T *&MemoryToFree2 = get_lvalue<T*>())
No this is not possible. You cannot use default paramters with references.
The following code complies fine for me using gcc 4.3.2.
void fn( int*const & i = 0 )
{
delete i;
}
so maybe you could adapt that. You need the *const
to permit the default argument.
Default arguments are permitted for references-to-const.
Edit
Just realised that marking it *const
is no use to you since you want to be able to null off the pointer as well as delete
it.