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
Derive a new class from std::map<K,V>
and create your own operator[]
. Have it return a const reference, which can't be used as an l-value.
Not sure why it compiles for you, I think the compiler should have caught your missing constructor.
what about using
map<K,V*>
instead of
map<K,V> ?
You can't make the compiler differentiate between the two uses of operator[], because they are the same thing. Operator[] returns a reference, so the assignment version is just assigning to that reference.
Personally, I never use operator[] for maps for anything but quick and dirty demo code. Use insert() and find() instead. Note that the make_pair() function makes insert easier to use:
m.insert( make_pair( k, v ) );
In C++11, you can also do
m.emplace( k, v );
m.emplace( piecewise_construct, make_tuple(k), make_tuple(the_constructor_arg_of_v) );
even if the copy/move constructor is not supplied.