Passing inline double array as method argument

Eric picture Eric · Jan 5, 2012 · Viewed 7.1k times · Source

Consider method

functionA (double[] arg)

I want to pass a double array inline, like

functionA({1.9,2.8})

and not create an array first and then pass it, like

double var[] = {1.0,2.0};
functionA(var);

Is this possible with C++? Sounds simple, but I could not find a hint anyway concerning my question which made me suspicious :).

Answer

Yuushi picture Yuushi · Jan 5, 2012

You can do this with std::initializer_list<>

#include<vector>

void foo(const std::initializer_list<double>& d)
{ }

int main()
{
    foo({1.0, 2.0});
    return 0;
}

Which compiles and works for me under g++ with -std=c++0x specified.