如果设置了可选函数参数,如何启用模板参数?
我有一个解析功能,我想根据设置长度选项是否设置。如果设置了长度选项,则该函数应始终检查缩短长度是否等于0。如果没有,则仅检查终止终止。 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);
}
让我困扰的是,我总是必须指定长度和模板参数才能使用长度选项。因此,我想知道:
- 是否有一种方法可以根据设置可选参数来进行constexpr分支?
- 我可以从设置可选参数中推断模板参数吗?
注意:这是一个人为的示例,只是显示细节。我在代码中添加了实际解析的评论。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您可以在此处使用功能过载:
I think you can use function overloading here:
您可以使用一对过载来执行此操作,该过载将其委派给模板版本以避免复制代码:
或者您可以切换到基于迭代的方法:
You can do this with a pair of overloads that delegate to a templated version to avoid duplicating code:
Or you can switch to an iterator-based approach: