How to store references as values in a std::map, and use operator overloading to access them?

65 views Asked by At

I'm trying to use a std::map where the values are stored as references. I've written a template Container class that should manage this, but I'm encountering issues with the Add() method and operator overloading.

Below is my code:

#include <stdio.h>
#include <map>
#include <string>

template<typename Key, typename Value>
class Container {
public:
    void Add(const Key& key, Value& value) {
        mMapContainer[key] = value;
    }
    
private:
    std::map<Key, Value&> mMapContainer;
};

int main() {
    Container<int, std::string> mContainer;
    
    std::string value = "value";
    
    mContainer.Add(1, value);
    
    printf("Hello World");

    return 0;
}

I want to store the values in the std::map as references, but as you might know, the Add() method isn't working as expected. How should I approach overloading operator[] and operator= to make this code functional?

0

There are 0 answers