How can I achieve a result like somebody would expect it 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 I thought would work spit out a compile error.
- How can I define an argument array directly in the line where the function is called?
If you were using C (C99, specifically), you could have used a compound literal here:
myFunction( (int []) {123, 456, 789} );
But the are not part of C++ (your compiler may still support them, though). In C++0x, you could use an initializer list, but they don't decay to pointers (not that using raw pointers is a good idea to begin with).
Although if you change the signature of myFunction to void myFunction( const int* arr )
, you would be able to do the contrived call
myFunction( std::initializer_list<int>({123, 456, 789}).begin() );
Something like what you are looking for is proposed as part of the C++0x standard. I don't believe there is a way to do it otherwise (currently).
void function_name(std::initializer_list<float> list);
function_name({1.0f, -3.45f, -0.4f});
You can't achieve that syntactic sugar with C++ code, not in C++03. The only place where braces are allowed, referring to elements of an array, is in initializing a named array:
int arr[] = { 0, 1, 2 };
Nowhere else. You can however achieve a similar effect with Boost.Assign:
void f(const std::vector<int>& v)
{
}
// ...
f(boost::assign::list_of(123)(456)(789));
You can do that, but you have to use two things:
use
std::vector
(or any other C++ STL class)use -std=c++0x compilation switch (or anything else for you compiler to use the c++0x standard).
精彩评论