c++ - 如何通过函数重载避免代码重复
问题描述
我有一对重载函数:
void func(const std::string& str, int a, char ch, double d) {
// piece of code A
sendMsg(str, a, ch, d);
// piece of code B
}
void func(int a, char ch, double d) {
// piece of code A
sendMsg(a, ch, d);
// piece of code B
}
piece of code A
和piece of code B
完全一样,唯一的区别是 的参数sendMsg
。
有没有办法避免代码重复?
解决方案
模板可能是一种可能性:
template <typename ... Ts>
auto func(const Ts&... args)
-> decltype(sendMsg(args...), void()) // SFINAE to only allow correct arguments
{
// piece of code A
sendMsg(args...);
// piece of code B
}
但移动// piece of code A
它自己的功能可能是我的选择。
推荐阅读
- php - 抓取带有特殊字符的 URL 参数
- dolphindb - 在 DolphinDB 中计算分组百分比
- pandas - Pandas 在特定列上显示格式
- c# - 如何将所有文档从一个 RavenDB 数据库移动到另一个?
- django - 在 Heroku 上托管的 Django 站点“没有运行 Web 进程”
- c# - Windows 窗体中的 Web 浏览器在使用窗体时不允许 ctrl+c。节目()
- r - 如何将列表中的元素用作ifelse中的条件
- java - Java 中的错误:不兼容的类型:LinkedList
无法转换为字符串 - powershell - 遍历脚本所在当前路径的所有文件夹
- r - 从Stata导入的R中的日期