Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

emplace_back and VC++ frustration

I'm using Visual Studio 2012, trying this both with the default compiler and the Nov CTP compiler, and the following below shows my problem:

struct doesCompile
{
    int mA, mB, mC, mD, mE;

    doesCompile(int a, int b, int c, int d, int e) : mA(a), mB(b), mC(c), mD(d), mE(e)
    { 
    }
};

struct doesNotCompile
{
    int mA, mB, mC, mD, mE, mF;

    doesNotCompile(int a, int b, int c, int d, int e, int f) : mA(a), mB(b), mC(c), mD(d), mE(e), mF(f)
    { 
    }
};


int _tmain(int argc, _TCHAR* argv[])
{
    std::vector<doesCompile> goodVec;
    goodVec.emplace_back(1, 2, 3, 4, 5);

    std::vector<doesNotCompile> badVec;
    badVec.emplace_back(1, 2, 3, 4, 5, 6);  //  error C2660: 'std::vector<_Ty>::emplace_back' : function does not take 6 arguments

    return 0;
}

Why on earth does it seem emplace_back is capped at a maximum of 5 arguments?? They even say in http://blogs.msdn.com/b/vcblog/archive/2011/09/12/10209291.aspx that it would take an arbitary amount of arguments..

Is there any way around this, using VS2012?

like image 659
KaiserJohaan Avatar asked Oct 05 '13 16:10

KaiserJohaan


People also ask

What is the function of Emplace_back?

This function is used to insert a new element into the vector container, the new element is added to the end of the vector. Syntax : vectorname. emplace_back(value) Parameters : The element to be inserted into the vector is passed as the parameter.

Which is faster Push_back or Emplace_back?

With the simple benchmark here, we notice that emplace_back is 7.62% faster than push_back when we insert 1,000,000 object (MyClass) into an vector.

Why Emplace_back is faster than pushback?

because emplace_back would construct the object immediately in the vector, while push_back , would first construct an anonymous object and then would copy it to the vector. For more see this question. Google also gives this and this questions.


2 Answers

It’s a restriction caused by the previous Visual C++ compiler architecture. Future versions of VC++ will lift that restriction and allow true variadic templates.

For the moment, you can statically raise the maximum limit of faux variadic templates by adding the following before any include into your code:

#define _VARIADIC_MAX 6

This will set the limit to 6 instead of 5 (up to a maximum possible value of 10) at the cost of decreased compilation speed.

like image 86
Konrad Rudolph Avatar answered Sep 26 '22 06:09

Konrad Rudolph


The VS2012 November CTP compiler supports variadic templates, but their Standard Library was not yet updated in that release. Should be fixed in VS2013RC. An upgrade is strongly recommended, because even the November CTP contained a lot of bugs. If not possible, use the macro mentioned by Konrad Rudolph.

like image 30
TemplateRex Avatar answered Sep 24 '22 06:09

TemplateRex