emplace_back with initializer list

231 Views Asked by At

I'm trying to run the following code on VS2022:

#include <vector>
#include <initializer_list>

int main()
{
    std::vector<std::vector<int>> vec;
    //auto list = (std::initializer_list<int>){ 5, 6 };
    vec.emplace_back((std::initializer_list<int>) { 5, 6 });
    return 0;
}

but it gives me an error:

Error C4576 a parenthesized type followed by an initializer list is a non-standard explicit type conversion syntax

and

expected an expression.

According to other answers this should work but it's not the case for me on VS2022, not even the commented line works. I tried compiling it using g++ and it was successful. Any ideas why?

1

There are 1 best solutions below

4
HolyBlackCat On

The C-style cast has the form (type)expression, and {...} isn't an expression (it doesn't have a type, and so on).

Probably the reason why this syntax isn't allowed is that C has something called compound literals with syntax (type){...}, with wildly different behavior compared to a cast, so reusing the same syntax in C++ for a different thing is probably a bad idea.

You want a functional cast, in the form type{...}. So, std::initializer_list<int>{5, 6}.

But if I was you, I'd use .push_back({5, 6}). Yes, this uses one extra move, but the syntax is cleaner.