简体   繁体   中英

Default parameter for a list reference

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
) 

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM