strlen()编译时间优化 [英] strlen() compile time optimization

查看:126
本文介绍了strlen()编译时间优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天前,我发现您可以使用以下内容找到编译时strlen:

Few days ago I discovered that you can find compile-time strlen using something like this:

template<size_t N>
constexpr size_t strlen_(const char (&data)[N]) noexcept{
    return N - 1;
}

如果已编译,那么一切都很好.您可以添加这样的重载:

If it's compiled, then all is good. You can add overload such this:

size_t strlen_(const char *s) noexcept{
    return strlen(s);
}

然后它将始终编译.

我的问题是-C ++ <cstring>是否使用类似的东西,如果没有,为什么?

My question is - does C++ <cstring> uses something like this and if it does not - why?

推荐答案

不,不是.因为它给出了错误的答案.

No, it doesn't. Because it gives the wrong answer.

char x[10] = "abc";
int correct_length   = std::strlen(x);  // 3
int incorrect_length = strlen_(x);      // 9

此外,如果您有2个重载,模板将永远不会被调用.始终首选接受const char*的非模板.

Also, with your 2 overloads, the template will never be called. The non-template one accepting a const char* will always be preferred.

这并不意味着在编译时无法使用某些编译器魔术来计算strlen.但这不能使用适当的语言来完成.

This doesn't mean that strlen can't be calculated at compile time with some compiler magic. But it can't be done this way, using the language proper.

这篇关于strlen()编译时间优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆