如何编写具有相同名称的相同函数,该函数在C++中几乎以相似的方式处理不同的类参数?



我有两个不同的类

class A_class {
public:
string member_to_add_to;
}

class B_class {
string member_to_add_to;
}

它们几乎相似,只是成员变量略有不同。不涉及继承。它们都用于不合并在一起的不同部分。我知道这不是一个好的设计,但我们现在没有时间修复它,因为代码库很大。

然后是Modifier类,它接受对A_classB_class对象的引用,并对类对象进行一些修改。

class Modifier() {
method1(A_class& object_ or B_class& object);
method2(A_class& object_ or B_class& object);
}

我需要在Modifier类中编写一个名为doSomething()的函数,该函数接受一个A_classB_class的对象以及一个字符串参数,该参数将成员变量member_to_add_to设置为字符串参数并调用Modifier中的其他方法。只有两行根据输入此函数的对象类型而有所不同。

void doSomething(A_class (or) B_class object_to_modify, string member_value) {
object_to_modify.member_to_add_to = member_value;
// after this 5 to 10 steps that call other methods taking a reference to object_to_modify but do the same thing
method1(object_to_modify);
method2(object_to_modify);
//etc.,
}

除了它涉及这两个类之外,此函数中的其他所有内容都是完全相同的代码。 我是否应该只对两个对象分别使用函数重载,并在 2 个函数中复制其中的代码两次,除了不同的行?

有没有更优化/可读的方法?

使用模板函数:

#include#include结构体 A { 字符常量* 数据; }; 结构体 B { 字符常量* 数据; }; 模板<类型名 A=">||std::is_same_v<T,>, int> = 0> void doSomething(T const& arg( { std::cout <<arg.data <<''; } int main(( { a a{"Hello "}; B b{"世界"}; 福(a(; 福(b(; foo("其他东西"(;不编译 }

稍微不那么混乱,有C++20个概念:

#include <concepts>
template <typename T>
void doSomething(T const& arg) requires (std::same_as<T, A> || std::same_as<T, B>) {
std::cout << arg.data << 'n';
}

如果这是一个常见问题,你甚至可以将这样的概念过度设计到你的代码库中:

模板<类型名称 _x002E_..类型=">概念 one_of = (std::same_as<T,> || ...(; 模板<A、B>T> void doSomething(T const& arg( { std::cout <<arg.data <<''; }

你可以使用模板:

template <typename AorB>
void doSomething(AorB& object_to_modify, string member_value) {
object_to_modify.member_to_add_to = member_value;
// after this 5 to 10 steps that call other methods taking a reference to object_to_modify but do the same thing
method1(object_to_modify);
method2(object_to_modify);
//etc.,
}

最新更新