c++ - 为什么不允许 `std::uniform_int_distribution<uint8_t>` 和 `std::uniform_int_distribution<int8_t>`?

标签 c++ c++11 random

作为 documentation says :

The effect is undefined if this is not one of short, int, long, long long, unsigned short, unsigned int, unsigned long, or unsigned long long.

如果我不关心范围,我可以屏蔽较大类型的位以生成随机数。如果不是,那就更复杂了。为什么不默认提供字节类型?

最佳答案

关于这个 uniform_int_distribution<unsigned char> should be permitted 有一个图书馆工作组未解决[1] 问题它说,除其他外:

I am not aware of anything in <random> that works with 16-bit integers but fails with 8-bit integers, so I suspect that IntType and UIntType could simply be extended to permit the char family. Alternatively, this change could be limited to uniform_int_distribution alone, where it is definitely safe. A <random> expert should decide which change is best.

建议的解决方案是更改限制以允许标准整数类型:

that has a template type parameter named IntType is undefined unless the corresponding template argument is cv-unqualified and is a a standard integer type (3.9.1 [basic.fundamental]

和:

that has a template type parameter named UIntType is undefined unless the corresponding template argument is cv-unqualified and is a standard unsigned integer type (3.9.1 [basic.fundamental])

这会让你得到 unsigned/signed char 虽然不是 uint8_tint8_t 但它们可能是等价的。排除了扩展的整数类型以简化措辞并最大限度地达成共识:

This also excludes extended integral types and wide char types, which seem like nice-to-haves at best. I have no objection to supporting any of those types; I just picked this to simplify the wording and hopefully maximize consensus.

注意,这不包括 char因为它是由实现定义的 char是否已签名。

请注意,该主题也在 std-discussion list 中提出。 .

Jonathan Wakely 指出该提案存在争议,并评论说他在上次讨论中的笔记包括以下内容:

that it was very definitely intentional that single byte integers are not supported, not an accidental omission, and so we should be careful about just changing that without consulting the designers of the C++11

他建议在 random_device 中添加一个成员提供单个字节,这似乎是一个合理的选择。


[1] 该问题已作为“Not A Defect”关闭,这意味着它不会作为缺陷报告解决。相反,需要一份正式的变更提案。

关于c++ - 为什么不允许 `std::uniform_int_distribution<uint8_t>` 和 `std::uniform_int_distribution<int8_t>`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31460733/

相关文章:

c++ - VirtualAlloc 在某些硬盘配置上失败

go - Go lang生成定长随机数

javascript - 数组中带有权重的随机数

c++ - 从守护进程启动的控制台应用程序捕获输出

java - ThreadLocalRandom 或 AtomicInteger

c++ - 创建对象数组时出现段错误

c++ - ifstream::seekg 给出错误的结果

c++ - 为什么从 base 转换为 derived 会提供此功能?

c++ - 在 C++11 中重置结构体值

visual-studio - 编译器可以通过调用 std::chrono::system_clock::now() 重新排序代码吗?