i try to do ordered map ( simple very simple ) i want to overload the map "[] = value " operator . that is the equal sign that come after the array operator but how ? i have this :
template <typename K, class V>
class OrderedMap
{
public:
OrderedMap(){};
~OrderedMap(){};
void setValue(K _k);
void operator[] (K _k);
private:
std::vector<K> insertOrder;
std::tr1::unordered_map<K, V> myTable;
};
template <typename K, class V>
OrderedMap<K, V>::setValue(K _k)
{
myTable[_k];
insertOrder.push_back(_k);
}
template <typename K, class V>
void OrderedMap<K, V>::operator[] (K _k)
{
......
}
i have the array set and working but how to add the option to add value to key via array operator so this will be vaild
m_Map[CONST1] = "value"
Basically operator[] is a function call which only supplies the parameters inside of the brackets to your class.
So in C++ you actually use the operator[] a bit different than let's say Delphi or C#: The operator[] usually returns a reference to the item inside the collection:
will actually resolve to the following:
the operator[] should then have the following form
If you cannot work with references for some reason (for example you don't actually HAVE a MyItem instance inside your container and the operator[] should convert the object into a different type) then the only approach is to use a "helper object":
the operator[] should then have the following form
where
MyHelper
is a special class which overloads the operator= which then does the container specific conversion (seevector<bool>
if you're interested in this approach).Edit: To come back to the problem: I'm a bit unsure what you exactly want to accomplish, but I think you'd need to use the "Helper" approach: