Create an object/Native demonstration: Difference between revisions
Create an object/Native demonstration (view source)
Revision as of 03:58, 7 February 2021
, 3 years agoC++ update
(Clarification?) |
(C++ update) |
||
Line 21:
{
// Two standard maps are used to implement FixedMap. One as a private
// base class
// Members of a private base class are not exposed to the derived class which will
// prevent keys from being added or deleted. Another map will hold copies of
Line 31:
: T(map), m_defaultValues(move(map)){}
// Expose members of the base class that
using T::begin;▼
using T::cbegin;
using T::end;▼
using T::cend;
using T::at;▼
using T::empty;
using T::find;
using T::size;
// Also expose members that can modify values but not add or remove keys.
▲ using T::at;
▲ using T::begin;
▲ using T::end;
// The [] operator will normally add a new key if the key is not already in the
// map. Instead, throw an error if the key is missing.
auto& operator[](typename T::key_type&& key)
{
}
//
//
void
{
T::operator[](key) = m_defaultValues.at(key);
}
// Also change the sematics of clear() to restore all keys
void clear()
{
// Reset the base class using the defaults
T::operator=(m_defaultValues);
}
};
Line 66 ⟶ 74:
cout << "{" << key << " : " << value << "} ";
}
cout << "\n\n";
};
Line 72 ⟶ 80:
{
// Create a fixed map based on the standard map
cout << "Map intialized with values\n";
FixedMap<map<
{"a", 1},
{"b", 2}});
PrintMap(fixedMap);
fixedMap["a"] = 55;
fixedMap["b"] = 56;
PrintMap(fixedMap);
fixedMap.
PrintMap(fixedMap);
cout << "Change the values the again\n";
fixedMap["a"] = 88;
fixedMap["b"] = 99;
PrintMap(fixedMap);
cout << "Reset all keys\n";
fixedMap.clear();
PrintMap(fixedMap);
try
{
// Adding or retrieving a missing key is a run time error
cout << "Try to add a new key\n";
fixedMap["newKey"] = 99;
}
Line 94 ⟶ 113:
{
cout << "error: " << ex.what();
}
}
</lang>
{{out}}
<pre>
{a : 1} {b : 2}
Change the values of the keys
{a : 55} {b : 56}
Reset the 'a' key
{a : 1} {b : 56}
error: key not found</pre>▼
Change the values the again
{a : 88} {b : 99}
Reset all keys
{a : 1} {b : 2}
Try to add a new key
=={{header|D}}==
|