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

I have the following two 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 a simple example of a problem that I want to solve.

Functions have the same body, but I need to handle both const and non const versions. I saw that this problem was handled using member functions using const const, but these are non-member functions, and I would like to solve this problem using a template. How can I write a boilerplate function that will reduce code duplication? I don’t even know where to start.

+4
source share
2 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 type is Map<String,Thing*>&
find_thing_by_name(s, const_m);    // MAP is deduced as const Map<String,Thing*>
                                   // thing_map type is const Map<String,Thing*>&
+4
source

, . ( const const-) , ( const). const. , , non const thing_map const Map & thing_map. const Thing * , it- > second Thing * not const Thing *. :

Thing* find_thing_by_name(const String & name, const Map<String,Thing*> & thing_map)
{
    auto it = thing_map.find(name);
    return it->second;
}

Thing, :

const Thing* find_thing_by_name(const String & name, const Map<String,Thing*> & thing_map)
{
    auto it = thing_map.find(name);
    return it->second;
}

:

...
const Map<String, Thing *> constMapObj;
const Map<String, Thing *> nonConstMapObj;
....
auto res1 = find_thing_by_name(someKey, constMapObj);
auto res2 = find_thing_by_name(someOtherKey, nonConstMapObj);
0

Source: https://habr.com/ru/post/1668580/


All Articles