评估在编译时不满意? [英] Evaluating strlen at compilation time?

查看:88
本文介绍了评估在编译时不满意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的代码包含此constexpr字符串

If my code has this constexpr string

constexpr char my_str[] = "hello";

my_str的类型包含有关其大小的信息,即sizeof(my_str)是常量6,可以在需要常量的任何地方使用.

the type of my_str contains information about its size, i.e. sizeof(my_str) is a constant 6, and can be used anywhere a constant is required.

strlen(my_str)怎么样?可以/也应该将其计算为编译时常数吗?

What about strlen(my_str)? Can/should it also be evaluated to a compile-time constant?

以下是是"的示例: https://ideone.com/2U65bN

以下是不提供示例: http://coliru.stacked-crooked.com/a/8cb094776dfc5969

标准对此有何表述?当然不是也许"吗?

What does the Standard say about this? Surely not "maybe"?

推荐答案

21.8、1和2在标准中表示:

21.8, 1 and 2, in the standard says:

  1. 表74、75、76、77、78和79描述了标头<cctype><cwctype><cstring><cwchar><cstdlib> (字符转换)和<cuchar>.

  1. Tables 74, 75, 76, 77, 78, and 79 describe headers <cctype>, <cwctype>, <cstring>, <cwchar>, <cstdlib> (character conversions), and <cuchar>, respectively.

这些标头的内容应与标准C库标头<ctype.h><wctype.h><string.h><wchar.h><stdlib.h>以及C Unicode TR标头<uchar.h>,其中 进行以下修改:

The contents of these headers shall be the same as the Standard C Library headers <ctype.h>, <wctype.h>, <string.h>, <wchar.h>, and <stdlib.h> and the C Unicode TR header <uchar.h>, respectively, with the following modifications:

strlen在c ++中的<cstring>中定义.后面的修改没有提到strlen.由此,我可以得出结论,C ++中的签名必须与C中的签名完全相同,并且由于C没有constexpr,因此在技术上不兼容.就是说,这是不合规的事情之一,除了在一个平台上依赖它,然后在另一个平台上找不到它之外,不太可能造成任何伤害.

strlen is defined in in <cstring> in c++. The modifications that follow do not mention strlen. From that, I would conclude that the signature in C++ must be exactly the same as it is in C, and since C does not have constexpr, it is technically non-compliant. That said, this is one of those non-compliant things that's unlikely to do any harm, beyond relying on it on one platform and then not finding it on another.

这篇关于评估在编译时不满意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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