Default value for pointer reference

I need to make the last argument in my function the default argument, and the type of this argument is *& (pointer reference). For some reason this does not work for me:

 template<class T> void f(T*& = nullptr); 

I get an error message:

Error 1 error C2440: "default argument": cannot convert from ' nullptr ' to ' T *& '

How to get around this?

+4
source share
3 answers

Basically, if you need to call this function using nullptr (which means that "I don't have a value to pass the function to, but you want to call it anyway"), you should take the argument as T** .

See How to pass objects to functions in C ++? for more information on passing arguments.

+1
source

If the argument is optional, it must be a pointer, not a reference.

 template<class T> void f(T** const = 0); 

If you want the call style to be passed by reference, you need a redirector, not a default argument.

 template<class T> void f_impl(T** const); template<class T> void f( T*& arg ) { return f_impl(&arg); } template<class T> void f( void ) { return f_impl<T>(0); } 

If you want to avoid null checks and simply refuse to assign to a parameter when the parameter is not set, do the following:

 template<class T> void f(T*&); template<class T> void f( void ) { T* unused = 0; return f(unused); } 

Note that T in the version with no arguments, is not an inferred context, but was also the original when the parameter was not provided.

+3
source

You have a l-value reference to a pointer, so you need to assign the value l by default. Since l-values โ€‹โ€‹cannot be nullptr (this is r value), or you will need to change the function to accept r value:

 template <typename T> void f(T const* const& = nullptr) 

or, define some l-value pointer for all types of T

 template <typename T> struct NullPtr { static T const* lvalue = nullptr; }; template <typename T> void f(T const*& = NullPtr<T>::lvalue) 

but I canโ€™t imagine why you really want the l value to be the default.

0
source

All Articles