I have a parsing function that I want to branch based on whether a length option is set or not. If the length option is set, the function should always check if the decreased length equals to 0. If not, it only checks for null termination. Based on this little detail I don't want to rewrite my whole function, so here's what I came up with:
#include <iostream>
const char* str = "some random string";
template <bool LengthOpt = false>
void parse(const char* ch, size_t len = 0)
{
while ( 1 ) {
if constexpr(LengthOpt) {
if ( len == 0 ) {
std::cout << std::endl;
return ;
} else {
len--;
}
} else {
if ( !(*ch) ) {
std::cout << std::endl;
return ;
}
}
std::cout << *ch;
++ch;
/* big part starts here */
}
}
int main()
{
parse<true>(str, 5);
parse(str);
}
What bugs me is that I always have to specify both, length AND template parameter to go with the length option. So I'm wondering:
- Is there a way to constexpr branch based on whether an optional parameter is set or not?
- Could I infer template parameters from whether the optional parameter is set?
Note: This is a contrived example showing just the detail. I've added comments in the code where the actual parsing would happen.