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?
All the elements in a map are stored in a key-value pair where each key is unique. Sorting is done with the help of keys and the values are associated with each key. Values can be inserted and deleted as and when required.
A C++ map is a way to store a key-value pair. A map can be declared as follows: #include <iostream> #include <map> map<int, int> sample_map; Each map entry consists of a pair: a key and a value.
The mapped values in a map can be accessed directly by their corresponding key using the bracket operator ((operator[]).
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With