my function looks like this
template<bool extra>
void func(int& arg1, const int arg2){
//a lot of code...
if (extra && arg2 > 0) ++arg1;
arg1 *= 10;
//a lot of code...
}
the problem is that when extra is false, arg2 is not used, but the function still requires it to be specified leading to unnecessary memory allocation for arg2 (you can check assembly output here). Is there any way to modify the function so that when extra is false, it only takes arg1, avoiding memory allocation for arg2 in that case?
This kind of problem is commonly solved using template specialization, which unfortunately typically requires a wrapper struct instead of the plain functions.
Here's an example how that could work:
Depending on the desired API, you can sometimes create a wrapper function or use
operator()to avoid the slightly ugly::runcalls.In your specific example, where the signature of the two function version differs (because you don't expect
arg2for theextra == truecase), you could even get away with basic function overloading:Note: If the template parameter should stay, a C++ 20
requiresclause orenable_ifguards instead of thestatic_asserts would express the intent of the function signature more accurately, currently at the cost of arguably worse error messages.