c++ - 如何为非常量和常量重载实现一次成员函数?
问题描述
有时我发现自己添加了具有相同实现的重载,其中const
in 限定符和返回值是唯一的区别:
struct B {};
struct A {
const B& get(int key) const
{
if (auto i = map.find(key); i != map.end())
return i->second;
throw std::runtime_error{""};
}
B& get(int key)
{
if (auto i = map.find(key); i != map.end())
return i->second;
throw std::runtime_error{""};
}
private:
std::unordered_map<int, B> map;
};
是否有一种惯用的方法可以只编写一次实现并摆脱比以下更好的复制粘贴const_cast
:
const B& get(int key) const
{
return const_cast<A*>(this)->get(key);
}
?
解决方案
斯科特迈耶斯的建议:
当 const 和 non-const 成员函数具有基本相同的实现时,可以通过让 non-const 版本调用 const 版本来避免代码重复。
推荐阅读
- echarts - 自定义颜色gridLine echarts
- spring - RouterFunction 无法注入处理程序 bean
- r - 在 R 中使用 rlist:merge.list 不起作用
- java - 什么是默认 JDBC 字符编码
- css - CSS:列数 + 变换 + 缩放 + 过渡 = 奇怪的行为
- wordpress - WordPress 众筹的不同捐赠账户
- angular - 如何在 Angular 构建库中声明一个 typings.ts 文件
- ios - UIAlertController 仅在特定时间
- android - Moshi 将值反序列化为 null
- javascript - TypeError: css.eachInside 不是 gulp.task 中的函数