Using std::map where V has no usable default constructor

后端 未结 9 1642
予麋鹿
予麋鹿 2020-12-05 13:11

I have a symbol table implemented as a std::map. For the value, there is no way to legitimately construct an instance of the value type via a default constructo

9条回答
  •  清歌不尽
    2020-12-05 13:35

    If the value-type is not default-constructible, then operator[] just won't work for you.

    What you can do, though, is to provide free functions that get and set values in a map for convenience.

    E.g:

    template 
    V& get(std::map& m, const K& k)
    {
        typename std::map::iterator it = m.find(k);
        if (it != m.end()) {
            return it->second;
        }
        throw std::range_error("Missing key");
    }
    
    template 
    const V& get(const std::map& m, const K& k)
    {
        typename std::map::const_iterator it = m.find(k);
        if (it != m.end()) {
            return it->second;
        }
        throw std::range_error("Missing key");
    }
    
    template 
    void set(std::map& m, const K& k, const V& v)
    {
        std::pair::iterator,bool> result = m.insert(std::make_pair(k, v));
        if (!result.second) {
            result.first->second = v;
        }
    }
    

    You might also consider a getter like dict.get(key [, default]) in Python (which returns the provided default if key is not present (but that has a usability problem in that the default always has to be constructed, even if you know that key is in the map).

提交回复
热议问题