Reputation: 12963
I tried to store a foo
object into a std::reference_wrapper
, but I end up with a compiler error I don't understand.
#include <functional>
#include <map>
struct foo
{
};
int main()
{
std::map< int, std::reference_wrapper< foo > > my_map;
foo a;
my_map[ 0 ] = std::ref( a );
}
The compiler error is pretty lengthy, but it boils down to this:
error: no matching function for call to ‘std::reference_wrapper<foo>::reference_wrapper()’
What exactly am I doing wrong?
Upvotes: 8
Views: 1884
Reputation: 44043
std::reference_wrapper
is not default-constructible (otherwise it would be a pointer).
my_map[0]
creates, if 0
is not already a key in the map, a new object of the mapped type, and for this the mapped type needs a default constructor. If your mapped type is not default-constructible, use insert()
:
my_map.insert(std::make_pair(0, std::ref(a)));
or emplace()
:
my_map.emplace(0, std::ref(a));
Upvotes: 9