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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With