Interminable
Interminable

Reputation: 1410

Declare array in function call

Right, I KNOW this is possible in C++0x/C++11, and therefore can be done in Visual Studio 2012.

HOWEVER, I am running Visual Studio 2010. I want to know if it is at all possible to do something similar to:

void MyFunction(int myArray[])
{}

MyFunction({1,2,3});

Without the inconvenience of having to declare the array beforehand.

Is there any workaround way of doing this in the version of C++ Visual Studio 2010 uses? Or somehow updating the compiler Visual Studio 2010 uses to support more C++11 features? Or am I out of options?

EDIT:

Thanks to yzt, I have been able to do this with Boost!

Here's some example code in case anyone else happens to be in my position (I don't seem to be able to use a normal array with this, but an std::vector (or indeed another stl container), etc will do just fine!):

The function:

void TestFunction(std::vector<int> myArray)
{
    for(std::vector<int>::size_type i = 0; i < myArray.size(); ++i)
    {
        std::cout<<myArray[i]<<std::endl;
    }
}

Calling it:

TestFunction(boost::assign::list_of(1)(2)(3));

Upvotes: 2

Views: 1790

Answers (4)

yzt
yzt

Reputation: 9113

I'm not sure about your exact use case, but you probably can use Boost.Assign to do this. And yes, it does work in VC10.

As has been posted in the comments, one can do like this:

TestFunction(boost::assign::list_of(1)(2)(3));

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490408

The only version (yet) of Visual C++ to support this directly is the Visual C++ 2013 Preview.

If you're really set on doing this, you can define an vector_builder class that will let you do the job in one line -- with a few provisos: first that it pretty much does have to be a vector instead of an array, and second that the syntax to do the job is quite ugly and counter-intuitive (to the point that I hesitate to even mention it at all).

template<class T>
class make_vector {
    std::vector<T> data;
public:
    make_vector(T const &val) { 
        data.push_back(val);
    }

    make_vector<T> &operator,(T const &t) {
        data.push_back(t);
        return *this;
    }

    operator std::vector<T>() { return data; }
};

template<class T> 
make_vector<T> makeVect(T const &t) { 
    return make_vector<T>(t);
}

With this, you'd call something like:

MyFunction((makeVect(1),2,3));

As I said, this strikes me as ugly enough that I hesitate to mention it at all -- but you may prefer it to the available alternatives.

Upvotes: 2

Anthony
Anthony

Reputation: 12407

The MSDN page outlining C++11 support in Visual Studio states that initialiser lists are not supported in VC10 or VC11.

Upvotes: 0

Richard Walters
Richard Walters

Reputation: 1474

Not possible in Visual Studio 2010, or in 2012, for that matter. Sorry!

Upvotes: 0

Related Questions