我有两个不同的类(class)class A_class {public: string member_to_add_to;}和class B_class { string member_to_add_to;}它们两者几乎相似,但成员变量略有不同。不涉及继承。它们都在不合并在一起的不同部分中使用。我知道这不是一个好的设计,但是由于代码量很大,我们现在没有时间修复它。然后是Modifier类,该类对A_class或B_class的对象进行引用,并对类对象进行一些修改。class Modifier() { method1(A_class& object_ or B_class& object); method2(A_class& object_ or B_class& object);}我需要在doSomething()类中编写一个称为Modifier的函数,该函数接受一个A_class或B_class的对象,以及一个将成员变量member_to_add_to设置为string参数并在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 <iostream>#include <type_traits>struct A { char const* data;};struct B { char const* data;};template <typename T, std::enable_if_t<std::is_same_v<T, A> || std::is_same_v<T, B>, int> = 0>void doSomething(T const& arg) { std::cout << arg.data << '\n';}int main() { A a{"Hello "}; B b{"World"}; foo(a); foo(b); // foo("something else"); // Doesn't compile}Slightly less cluttered with C++20 concepts:#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';}如果这是您遇到的常见问题,您甚至可以在代码库中过度设计这样的概念:模板概念one_of =(std::same_as || ...);模板 T>void doSomething(T const&arg){ std::cout }
10-04 23:17
查看更多