Reputation: 447
I am coding a C++ library and one class has two member functions that only differ in one function call:
int MyClass::member_func_1(int a) {
// ...
int b = some_function();
// ...
}
int MyClass::member_func_2(int a) {
// ...
int b = some_other_function();
// ...
}
Is there a way of not having to duplicate the code of these two functions, while still keeping the two member functions with the same function signatures?
some_function
and some_other_function
for performance reasons.Upvotes: 1
Views: 246
Reputation: 52417
You may use a boolean for switching the internal method to be called or pass a function pointer / std::function and call that one directly. the performance penalty will be ridiculously negligible.
If you really want to make your code less readable because of that virtually non-existant "performance reason", you can implement the common method templated, with a boolean template parameter. The if() clause referring the template parameter can then be a constexpr (realised during compilation).
However note that this will also lead to the method being effectively doubled in your applications code, and when you have many alternating calls, this might have an adverse effect on your performance similar to the original if() clause, i.e. not noticable at all.
Upvotes: 1
Reputation: 60440
Since the only difference in the implementation of your two member functions is the calls to different member functions, that's what you should abstract out of those functions. You can do that by writing a single member function that takes a pointer to member function as an additional argument:
int common_member_func(int a, int (MyClass::*func)())
{
// ...
int b = (this->*func)();
// ...
}
and now the implementation of your two member functions would be:
int member_func_1(int a)
{
return common_member_func(a, &MyClass::some_function);
}
int member_func_2(int a)
{
return common_member_func(a, &MyClass::some_other_function);
}
Here's a demo.
Upvotes: 4
Reputation: 6898
A template
solution is only a good solution if the call to either of the member functions is executed in a tight loop, where the overhead of testing a boolean or making an indirect function call would be too costly.
In this case, if C++17 standard is an option, the if constexpr
syntax is probably the simplest way. Like in:
class MyClass
{
template<bool other> int member_func(int a)
{
//...
int b;
if constexpr (other)
b = some_other_function();
else
b = some_function();
//...
}
};
Upvotes: 6