将方法传递给方法并替换(几乎完全相同)重复代码
pass method to method and replace (almost exactly same) repeating code
我有两种非常相似的方法。他们之间的主要区别在于他们在某个时候调用了另一种不同的方法。例如:
// method 1
method1(){
// same code for Method1 and Method2 before calling different method
methodA();
// same code for Method1 and Method2 after calling different method
}
// method 2
method2(){
// same code for Method1 and Method2 before calling different method
methodB();
// same code for Method1 and Method2 after calling different method
}
我想创建一个方法(method
(,该方法将能够调用两个不同的方法(methodA
和methodB
(。我想这应该通过多态性(如果我错了,请正确正确(,例如:
method(Parent obj){
// same code for Method1 and Method2 before calling different method
obj->methodAB();
// same code for Method1 and Method2 after calling different method
}
class Parent{
public:
virtual int methodAB();
};
// methodA implementation
Class ChildA: public Parent{
public:
int methodAB();
}
// methodB implementation
Class ChildB: public Parent{
public:
int methodAB();
}
实际呼叫将是:
Parent *obj = new ChildA; // or Parent *obj = new ChildB;
method1(obj)
delete obj;
但是有一个严重的问题:在我的情况下,methodA()
和methodB()
作为参数不同的类型,因此我的情况实际上是:
method1(obj_type1){
// same code for Method1 and Method2 before calling different method
methodA(obj_type1);
// same code for Method1 and Method2 after calling different method
}
method2(obj_type2){
// same code for Method1 and Method2 before calling different method
methodB(obj_type2);
// same code for Method1 and Method2 after calling different method
}
是否可以在带有不同类型的参数的派生类中实现虚拟函数,还是有其他优雅的解决方案来解决此问题?
因此,将常见代码重构到其他功能中,并调用两个方法(成员函数(:
:method1(){
common_code_1();
auto result = methodA(obj_type1);
common_code_2(result);
}
method2(){
common_code_1();
auto result = methodB(obj_type2);
common_code_2(result);
}
您可以使用模板去做您想做的事,这些行:
void foo1(int i)
{
}
void foo2(double d)
{
}
template<typename ArgType, void (*Func)(ArgType arg)>
void DoIt(ArgType a)
{
// Common 1
Func(a);
// Common 2
}
int main()
{
DoIt<int, foo1>(1);
DoIt<double, foo2>(1.0);
return 0;
}
Func
不需要是 void
,它可以返回 bool
,或者如果您需要进行处理。
相关文章:
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 如何重写全局方法名称以在调用原始方法之前将我的代码推到前面
- 在nodejs中使用本机代码的最佳方法是什么?
- 函数从唯一代码调用正确的子类方法
- 如何启用使用另一个类的静态方法的模板函数的自动推导,从而消除冗长的调用方代码
- 有没有更好的方法来编写这个c++代码
- 终端进程终止,退出代码为:1有什么方法可以修复它吗
- 有没有一种预处理器的方法可以从调试符号中删除代码段
- C++:销毁此代码的最佳方法是什么?
- 在.cpp文件中定义方法而不是在 C++ 的 .h 文件中定义方法时,如何提高代码的性能?
- 为什么在我的代码中没有调用 g 模拟方法
- 设计许多单例代码结构的更好方法
- 两种专用方法中的相同代码
- Android 无法从本机代码调用 Java 方法 JNI
- 我的类中有方法的指针数组,但我不能调用我的方法.代码如下
- 如何在子类中获得相同的方法代码而不重复代码
- 如何只执行一次方法代码,尽管每帧调用一次
- 模板化的方法代码在哪里分配?