EDIT: note I want a static compile time method, when I know exactly what needs to go where at compile time.
I often find myself having multiple functions which follow the same pattern, but only a few parts change. Often I opt for the Template Method Pattern, however class based approaches (especially in c++) seem very cumbersome. I'm often forced to create actual objects when really all I'm trying to do is change one line for another that can't be prepended or appended to the routine I'm writing, where ideally I'd want to simply generate a function given a pattern at compile time. I even need to create private/protected classes where the procedure only makes sense in the class I'm using. This all seems like a huge waste.
I'd like a static approach to this, where I know exactly which function I would like to use in each situation, but I don't want duplicated code between each function where only a small amount changes. Is it possible in something like C++ with out resorting to creating custom classes for each case this happens? There are "solutions" like creating several custom functions for each step, but with out TMP these functions become coupled to a high degree and require way more parameters to be passed around than normally needed, and still never really seem to get rid of code duplication.
EDIT most recent example I came across since I was asked for examples...
class X{
A m_class_member_1;
B m_class_member_2;
C m_class_member_3;
D m_class_member_4;
E m_class_member_5;
...
void duplicateProcedure_1(){
auto some_value = m_class_member_1.function();
if(valuePassesTest(some_value)){
auto some_other_value = m_class_member_2.function(some_value);
m_class_member_3.function(some_other_value);
m_class_member_4.function(some_other_value);
// changed procedure
m_class_member_5.function_1(some_other_value);
}
}
void duplicateProcedure_2(){
auto some_value = m_class_member_1.function();
if(valuePassesTest(some_value)){
auto some_other_value = m_class_member_2.function(some_value);
m_class_member_3.function(some_other_value);
m_class_member_4.function(some_other_value);
//changed procedure
m_class_member_5.function_2(some_other_value);
}
}
}
the last line in each is the only thing that needs to be changed, everything else needs to be the same, but they also depend on variables created with in the procedure, as well as conditions outside the scope of their block.
if
body to a new method called from both places?some_other_value
replacing all but the last line likeif(valuePassesTest(some_value)){m_class_member_5.function_2(this.new_function_replacing_previous_lines(some_value));}