một lần tôi nhìn thấy đoạn mã sau:
void doSomethingGeneric1(SomeClass * c, SomeClass & d)
{
// three lines of code
callFunctionGeneric1(c) ;
// three lines of code
}
lặp đi lặp lại mười lần:
void doSomethingGeneric2(SomeClass * c, SomeClass & d)
void doSomethingGeneric3(SomeClass * c, SomeClass & d)
void doSomethingGeneric4(SomeClass * c, SomeClass & d)
// Etc
Mỗi chức năng có cùng 6 dòng mã sao chép/dán, và mỗi lần gọi khác function callFunctionGenericX với cùng một hậu tố số.
Không có cách nào để cấu trúc lại toàn bộ mọi thứ. Vì vậy, tôi giữ refactoring địa phương.
tôi đã thay đổi mã theo cách này (từ bộ nhớ):
template<typename T>
void doSomethingGenericAnything(SomeClass * c, SomeClass & d, T t)
{
// three lines of code
t(c) ;
// three lines of code
}
Và sửa đổi mã hiện với:
void doSomethingGeneric1(SomeClass * c, SomeClass & d)
{
doSomethingGenericAnything(c, d, callFunctionGeneric1) ;
}
void doSomethingGeneric2(SomeClass * c, SomeClass & d)
{
doSomethingGenericAnything(c, d, callFunctionGeneric2) ;
}
vv
này hơi highjacking mẫu điều, nhưng cuối cùng, tôi đoán nó tốt hơn so với chơi với con trỏ hàm typedefed hoặc sử dụng macro.
Ya. ví dụ tuyệt vời. Cảm ơn. – EvilTeach