Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Now I have a function in C++

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

I hope the argument 'x' could 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 a function argument, the code

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

will make compiler error.


I test in MSVC 2012, and got error C2143, C2059, C2447. And also error in g++ 4.6.3


Is there any way make it has a default value?

thanks.

like image 950
Heresy Avatar asked Dec 21 '22 06:12

Heresy


1 Answers

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

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

This is because std::array just has a C array underneath and initialize it with aggregate initialization. The first pair of braces are for the list initialization list while the second pair of braces is for the C-array initialization.

According to the standard (8.5.1.11), the outer braces can be elided in such a case if (and only if) you use the sign = for initialization. However, some compilers still do not support this behaviour (g++ being one of them).

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

like image 73
Morwenn Avatar answered Dec 22 '22 20:12

Morwenn