samedi 24 septembre 2016

Aggregate initialization doesn't work with emplace? [duplicate]

This question already has an answer here:

I have the following piece of code:

#include <string>
#include <vector>

using namespace std;

struct employee {
  string first;
  string last;
};

int main() {
  vector<employee> v;
  v.push_back(employee{"John", "Smith"});
}

which works. But as soon as I use emplace_back instead of push_back I get errors:

#include <string>
#include <vector>

using namespace std;

struct employee {
  string first;
  string last;
};

int main() {
  vector<employee> v;
  v.emplace_back("John", "Smith");
  // changing to e.g. string("John"), string("Smith") doesn't change anything
  // this works (taking rvalue)
  //v.emplace_back(employee{"John", "Smith"});
}

error:

In file included from /usr/include/x86_64-linux-gnu/c++/5/bits/c++allocator.h:33:0,
                 from /usr/include/c++/5/bits/allocator.h:46,
                 from /usr/include/c++/5/string:41,
                 from /usr/include/c++/5/bits/locale_classes.h:40,
                 from /usr/include/c++/5/bits/ios_base.h:41,
                 from /usr/include/c++/5/ios:42,
                 from /usr/include/c++/5/ostream:38,
                 from /usr/include/c++/5/iostream:39,
                 from main.cpp:2:
/usr/include/c++/5/ext/new_allocator.h: In instantiation of ‘void __gnu_cxx::new_allocator< <template-parameter-1-1> >::construct(_Up*, _Args&& ...) [with _Up = employee; _Args = {const char (&)[5], const char (&)[7]}; _Tp = employee]’:
/usr/include/c++/5/bits/alloc_traits.h:530:4:   required from ‘static void std::allocator_traits<std::allocator<_Tp> >::construct(std::allocator_traits<std::allocator<_Tp> >::allocator_type&, _Up*, _Args&& ...) [with _Up = employee; _Args = {const char (&)[5], const char (&)[7]}; _Tp = employee; std::allocator_traits<std::allocator<_Tp> >::allocator_type = std::allocator<employee>]’
/usr/include/c++/5/bits/vector.tcc:96:30:   required from ‘void std::vector<_Tp, _Alloc>::emplace_back(_Args&& ...) [with _Args = {const char (&)[5], const char (&)[7]}; _Tp = employee; _Alloc = std::allocator<employee>]’
main.cpp:15:34:   required from here
/usr/include/c++/5/ext/new_allocator.h:120:4: error: no matching function for call to ‘employee::employee(const char [5], const char [7])’
  { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
    ^
main.cpp:8:8: note: candidate: employee::employee()
 struct employee {
        ^
main.cpp:8:8: note:   candidate expects 0 arguments, 2 provided
main.cpp:8:8: note: candidate: employee::employee(const employee&)
main.cpp:8:8: note:   candidate expects 1 argument, 2 provided
main.cpp:8:8: note: candidate: employee::employee(employee&&)
main.cpp:8:8: note:   candidate expects 1 argument, 2 provided

Aucun commentaire:

Enregistrer un commentaire