-1

I want to set an empty list as a default value to the list argument. I've tried using {}, list.(), NULL, and {NULL} to no avail.

void f(std::list<treeNode*> &path = ??);

When {} is used,

error: could not convert ‘<brace-enclosed initializer list>()’ from ‘<brace-enclosed initializer list>’ to ‘std::list<treeNode*>&’

When list<treeNode*>() is used,

error: expected primary-expression before ‘.’ token
 void f(treeNode* root, int &n, list<treeNode*> &path = list<treeNode*>.()){
tejasvi88
  • 635
  • 7
  • 15
  • You didn't have `&` in your original example. That's important to know. – David G Jun 03 '19 at 02:33
  • Pretty much a duplicate now, as it's the same for all references, not just `std::list`: https://stackoverflow.com/questions/1059630/default-value-to-a-parameter-while-passing-by-reference-in-c – Tas Jun 03 '19 at 02:41

1 Answers1

3
void f(std::list<treeNode*> = ??);

You can use a pair of empty curly brackets:

void f(std::list<treeNode*> = {});

I've tried using ... list.()

This is a syntax error.

NULL,

A std::list cannot be initialised from a pointer constant.

and {NULL}

This initialises a non-empty list with a single null element.

{} ... to no avail.

This is the correct solution since C++11. In pre-C++11 standards, you would have had to repeat the type name:

void f(std::list<treeNode*> = std::list<treeNode*>())

Edit regarding the new question:

void f(std::list<treeNode*> &path = ??);

This is different. A non-const lvalue reference cannot be bound to an initialiser list. You have to either:

  1. Use a const lvalue reference argument.
  2. Or use an rvalue reference argument.
  3. Or initialise the non-const lvalue reference to some static object by default... Which is not a good option if the function changes the argument. If the argument is not chnaged, use 1. instead.
eerorika
  • 232,697
  • 12
  • 197
  • 326