首页 > 解决方案 > 如何通过函数重载避免代码重复

问题描述

我有一对重载函数:

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 Apiece of code B完全一样,唯一的区别是 的参数sendMsg

有没有办法避免代码重复?

标签: c++c++11overloading

解决方案


模板可能是一种可能性:

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它自己的功能可能是我的选择。


推荐阅读