Suppose I have a class that wraps a dictionary (std::map
). The class has getter and setter to manipulate values. To simplify the code I would like to have some helper function that will provide access to a specified node by name. The problem that such a function should be called from both const and non-const context.
The code is as follows:
class MyTest
{
public:
void set(const std::string_view &name, const std::string_view &value)
{
auto *it = get_private(name);
if(it != nullptr)
{
*it = value;
}
else
{
m_arr.insert({name, value});
}
}
std::string_view get(const std::string_view &name) const
{
auto *it = get_private(name);
if(it != nullptr)
{
return *it;
}
return "";
}
private:
const std::string_view *get_private(const std::string_view &name) const
{
auto it = std::find_if(m_arr.begin(), m_arr.end(), [name](const auto &pair) -> bool {
return pair.first == name;
});
if(it == m_arr.end())
{
return nullptr;
}
return &(it->second);
}
std::string_view *get_private(const std::string_view &name)
{
auto it = std::find_if(m_arr.begin(), m_arr.end(), [name](const auto &pair) -> bool {
return pair.first == name;
});
if(it == m_arr.end())
{
return nullptr;
}
return &(it->second);
}
private:
std::map<std::string_view, std::string_view> m_arr;
};
and usage as follows:
MyTest mt;
mt.set("name1", "value1");
mt.set("name2", "value3");
std::string_view v = mt.get("name1");
std::cout << v << std::endl;
But I don't like the idea to have 2 versions of the helper function - const and non-const.
I'm thinking of something like this:
template <typename T>
typename std::conditional<std::is_same<T, std::string_view>::value, std::string_view, const std::string_view>::type
*get_private(const std::string_view &name)
{
}
but I have no clue how to make the function itself const/non-const. Anyway I get the error:
Candidate template ignored: couldn't inter template argument 'T'
How can I declare such a function?
P.S. According to the Misra/Autosar rules I can't use const_cast
casting.