I have the two following functions:
Thing* find_thing_by_name(const String & name, Map<String,Thing*> & thing_map)
{
auto it = thing_map.find(name);
return it->second;
}
const Thing* find_thing_by_name(const String & name, const Map<String,Thing*> & thing_map)
{
auto it = thing_map.find(name);
return it->second;
}
This is just a simple example for an issue that I want to solve.
The functions have the exact same body, but I need both to handle const and non const versions of my maps. I've seen this issue handled with member functions using a const cast, but these are nonmember functions and I would like to solve this issue using a template. How can I write a templated function that will reduce code duplication? I'm not even sure where to start.
You can:
template <typename MAP>
auto find_thing_by_name(const String & name, MAP & thing_map)
{
auto it = thing_map.find(name);
return it->second;
}
then
String s = ...;
Map<String,Thing*> nonconst_m = ...;
const Map<String,Thing*> const_m = ...;
find_thing_by_name(s, nonconst_m); // MAP is deduced as Map<String,Thing*>
// thing_map's type is Map<String,Thing*>&
find_thing_by_name(s, const_m); // MAP is deduced as const Map<String,Thing*>
// thing_map's type is const Map<String,Thing*>&
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With