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.

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.


Need Your Help

PHP Parse $_POST Array?

php arrays parsing

A server sends me a $_POST request in the following format:

resize image in table view cell

iphone ios

resize a image in table view cell... i am new programmer

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.