C ++: pass array created in function call string

How can I achieve the result, as someone would expect according to the following code example:

// assuming: void myFunction( int* arr );

myFunction( [ 123, 456, 789 ] );

// as syntactical sugar for...

int values[] = { 123, 456, 789 };
myFunction( values );

The syntax that I thought would work spits out a compilation error.

  • How to define an array of arguments directly in the line where the function is called?
+5
source share
4 answers

You cannot achieve this syntactic sugar with C ++ code, not C ++ 03. The only place where parentheses are allowed when referring to array elements is to initialize the named array:

int arr[] = { 0, 1, 2 };

Nowhere. However, you can achieve a similar effect with Boost.Assign:

void f(const std::vector<int>& v)
{
}

// ...
f(boost::assign::list_of(123)(456)(789));
+3
source

- , , ++ 0x. , ( ).

void function_name(std::initializer_list<float> list);

function_name({1.0f, -3.45f, -0.4f});
+3

C (C99, ), :

myFunction( (int []) {123, 456, 789} );

++ ( ). ++ 0x , ( , - ).

myFunction void myFunction( const int* arr ),

myFunction( std::initializer_list<int>({123, 456, 789}).begin() );
+3

, :

  • std::vector ( ++ STL)

  • -std = ++ 0x ( - ++ 0x).

+1

All Articles