I’m fairly new to programming in c and would like to ask how to implement something in the most efficient way. Let’s say I got a class A with two functions foo and bar. Main will instantiate and object of A and will call foo. This class does something computationally expensive, where foo might call bar and vice versa, backtrack and so on until some result is computed. I now would like to implement something like a decorator for this class where the function bar now does the same as before but before returning e.g., prints some intermediate result, while keeping the original implementation available for cases in which these intermediate results are not wanted. Everything else stays the same.
I wonder I would implement something like this in the best way. I could of course add some if statement at the end of bar in class A and check some member variable which is set in main, but as these functions will be called a lot, this would add many additional checks which are not really needed, as one check in main would be sufficient. I could also create a copy of class A, let’s call it B, and modify bar there. But this would duplicate most of the code and would require subsequent changes to be made to both A and B. I could also make function bar in A virtual and have B derive from A and overwrite it, but then I would just simply have these checks in form of the dispatching decisions, wouldn’t I?
CodePudding user response:
I would recommend to use a bool parameter
class A{
public:
void foo(/*params*/,bool should_print=false){
if (should_print){
//print
}
}
void bar(/*params*/,bool should_print=false){
if (should_print){
//print
}
}
};
If you want to print set the parameter should_print to true, otherwise don't pass it.
You can also use template for flag. so (INside class A)
template<bool should_print>
void bar(/*params*/){
if constexpr (should_print){
//print
}
}
This will evaluate the if at compile-time so it will be even faster, but you will have to define template-funkctions in the heather for the class not in it's .cpp
Note if constexpr
only works from c 17
you can have a regular if
if you use an older standard. any competent compiler will evauleate the if compile-time that way too