* Ramprasad A Padmanabhan:
Suppose I have a function that expects an array as argument
{
....
int d[] = { 1,2,3,4}
someFunc(d);
}
I have to create a temporary array d[] and pass 'd' to the function.
Can I avoid the the temporary array
something like
{
....
someFunc({1,2,3,4});
.....
}
Well, there are three issues:
* Avoiding an _automatic_ (local variable) array.
* Specifying the values of a conceptual array in a function call.
* Efficiency of such a specification.
Regarding how to avoid a local variable, initialized each time, if
concurrency is not an issue you can declare the array static:
static int const d[] = {1, 2, 3, 4};
somefunc( d );
Regarding how to specify the values of a conceptual array in a function
call C++ doesn't have a notation for that, so it reduces to the general
problem of specifying an arbitrary number of arguments. The usual
solution, e.g. employed by std::cout "<<", is to use a member operator
or function that returns a reference to the object it's called on. Like
(disregarding issues related to deriving from a class with no virtual
constructor -- you might want to use encapsulation instead)
class Array: public std::vector<int>
{
public:
Array& operator<<( int x ){ push_back( x ); return *this; }
};
inline Array const& temporary( Array const& a ){ return a; }
...
d( temporary( Array() << 1 << 2 << 3 << 4 ) );
Possibly there is such a thing in Boost, <url:
http://www.boost.org>, I
think I saw something like that.
Regarding efficiency, first make correct, then check if good enough,
then if it isn't, measure (unless obvious), and only then optimize.