Каков правильный способ инициализировать класс и напрямую назначить unordered_map?
#include <string>
#include <unordered_map>
int main() {
std::unordered_map<std::string, Foo> s;
// Foo foo{1};
s["test"] = Foo(1); // this is bad
return 0;
}
Foo.h
class Foo {
public:
Foo(int x)
: x_(x) {}
private:
int x_;
};
Теперь я получаю
main.cpp:19:4: note: in instantiation of member function 'std::unordered_map<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, Foo, std::hash<std::__cxx11::string>, std::equal_to<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<const std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, Foo> > >::operator[]' requested here
s["test"] = Foo(1);
^
Foo.h:3:5: note: candidate constructor not viable: requires single argument 'x', but no arguments were provided
Foo(int x)
^
Foo.h:1:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided
class Foo {
^
Foo.h:1:7: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 0 were provided
Проблема связана с s["test"] = Foo(1)
.