Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default parameter for a list reference

Tags:

c++

default

In C++, how would I specify a default value for a list reference in a function?

void fun(
  std::list<My_Object *> &the_list,
  int n = 4
) 
like image 233
Tim Avatar asked Feb 04 '23 00:02

Tim


2 Answers

if it is a plain reference, the only thing you an default it to is a valid lvalue which probably is not available. But if it is a reference to const you could default it to an empty list like this:

void fun(
  std::list<My_Object *> const & the_list = std::list<My_Object *>(),
  int n = 4
) 

If you have a list named a, which is available at the declaration site, then like this

void fun(
      std::list<My_Object *> & the_list = a,
      int n = 4
    ) 

but be careful so that the a list is still "alive" when you call the function

like image 117
Armen Tsirunyan Avatar answered Feb 06 '23 14:02

Armen Tsirunyan


In C++, how would I specify a default value for a list reference in a function?

I wouldn't, in your case. Either overload the function so that it can be called without a list, or take the argument per pointer, so that users can pass a NULL pointer.

I'd strongly prefer overloading.

like image 42
sbi Avatar answered Feb 06 '23 15:02

sbi