C ++ function call with default argument in std :: array?

I now have a function in C ++

void F( std::array<int,3> x ) { //... } 

I hope the argument "x" can have a default value, how can I do this?

If not a function argument, I can simply use

 std::array<int,3> x = {1,2,3}; 

But for the function argument, the code

 void F( std::array<int,3> x = {1,2,3} ) { //... } 

will make a compiler error.


I am testing in MSVC 2012 and received error C2143, C2059, C2447. And also a bug in g ++ 4.6.3


Is there any way to make this the default?

thanks.

+4
source share
1 answer

Your solution should work in accordance with the standard, but not implemented in some compilers. Most of them can initialize std::array instances with the syntax x = {{1,2,3}} rather than with x = {1, 2, 3} . If you want it to work today, your function should be:

 void F( std::array<int,3> x = {{1,2,3}} ) { //... } 

This is because std::array just contains a C array and initializes it using aggregate initialization . The first pair of curly braces is for the list initialization list, and the second pair of curly braces is for the initialization of the C-array.

In accordance with the standard (8.5.1.11), external curly braces can be excluded if (and only if) you use the = sign to initialize. However, some compilers still do not support this behavior (g ++ is one of them).

And as a bonus, you can check it online with ideone.

+11
source

All Articles