i'm writing a class CScope
holding variables (string -> value associations). I would like to create a method that would allow me to access CValue
objects by reference but that would behave in two different ways depending on the fact that we access it for reading or writing.
Here is what i have so far :
class CScope
{
PROTECTED map<string, CValue> _mVars;
PUBLIC inline const CValue & access( const string & __rsName ) const
{
map<string, CValue>::const_iterator oItr = this->_mVars.find( __rsName );
if( oItr != this->_mVars.end() )
{
return oItr->second;
}
else
{
throw; // TODO Error.
}
}
PUBLIC inline CValue & access( const string & __rsName )
{
map<string, CValue>::iterator oItr = this->_mVars.find( __rsName );
if( oItr != this->_mVars.end() )
{
return oItr->second;
}
else
{
return this->_mVars.insert_at(
}
}
};
If we access in read-only (const) and if the variable doesn't exist, an error has to be raised. However if we access in write mode (not const), i want the variable to be created if it doesn't exist. Like in PHP :
$undeclaredVar = 10; // OK, no need to declared it. = accesses in write mode.
$undeclaredVar = $otherUndeclaredVar + 10; // Error, + accesses in read mode.
In the case where i access in write mode, I would like to avoid being forced to first insert the value and then find it, because it would cause 2 hash calculations and i want something optimized.
Isn't there a method in std::map that allows me to insert a value and get the iterator to the newly inserted element without having to compute the hashing (and any other expensive work) twice ? Insert seems to do that but it doesn't seem to have the overload i need, i.e iterator insert( const key &, const value & )
Thank you :)
EDIT :
I found a way :
return this->_mVars[ __rsName ]; // Operator[] creates if not found.