The following code compiles
#include <vector>
struct Foo
{
int a;
int b;
};
int main()
{
std::vector<Foo> foos;
foos.emplace_back(Foo{1, 2});
}
However, it fails if I replace struct
with class
1. Aside from doing that (I would like to keep the members private), is there something I can do to enable me to use the Foo{1, 2}
notation? I'm keen to avoid writing a constructor for Foo
myself.
I'm using C++17 although of course will be interested in general C++ answers.
1 Compile error (MSVC) is
1>c:\...: error C2440: 'initializing': cannot convert from 'initializer list' to 'Foo'
1>c:\...: note: No constructor could take the source type, or constructor overload resolution was ambiguous
1>c:\...: error C2672: 'std::vector<Foo,std::allocator<_Ty>>::emplace_back': no matching overloaded function found
1> with
1> [
1> _Ty=Foo
1> ]
Aucun commentaire:
Enregistrer un commentaire