Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reducing code duplication for const and non const nonmember functions using a template

Tags:

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.

like image 475
Dillydill123 Avatar asked Feb 02 '17 05:02

Dillydill123


1 Answers

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*>&
like image 56
songyuanyao Avatar answered Sep 21 '22 10:09

songyuanyao