mardi 3 janvier 2017

c++ unordered hash map with deleted default constructor

Trying to figure out why inserting an element into an STL unordered hash map needs the VALUE_TYPE to have a default constructor.

say I have something like below, where we explicitly deleted the default constructor.

class TestClassVal {
public:
    TestClassVal() = delete;
    TestClassVal(int i) : i{ i } {}
private:
    int i;
};

class TestClass {
public:
    TestClass() = delete;
    explicit TestClass(int max_keys) : max_keys{ max_keys } {}
    void insert(string key, int val) {
        if (m.size() < max_keys) {
            m[key] = val;
        }
    }
private:
    int max_keys;
    unordered_map<string, TestClassVal> m;
};

when we compile above (visual studio 2015) gives the error below.

Error C2280 'TestClassVal::TestClassVal(void)': attempting to reference a deleted function

This is happening in the std::tuple implementation of the STL:

        : first(_STD get<_Indexes1>(_STD move(_Val1))...),
        second(_STD get<_Indexes2>(_STD move(_Val2))...)

Unordered hashmap implementation seems to use a tuple possible this code:

    template<class _Keyty,
    class... _Mappedty>
    _Pairib _Try_emplace(_Keyty&& _Keyval,
        _Mappedty&&... _Mapval)
    {   // fail if _Keyval present, else emplace
    iterator _Where = _Mybase::find(_Keyval);
    if (_Where == _Mybase::end())
        return (_Mybase::emplace(
            piecewise_construct,
            _STD forward_as_tuple(_STD forward<_Keyty>(_Keyval)),
            _STD forward_as_tuple(_STD forward<_Mappedty>(_Mapval)...)));
    else
        return (_Pairib(_Where, false));
    }

Question

  1. does STL mandate types to have default constructors?
  2. How do I get around this problem. I do not want to really have a default constructor.

Aucun commentaire:

Enregistrer un commentaire