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 有一个图书馆工作组 Unresolved [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])

虽然不是 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] 该问题已作为“不是缺陷”关闭,这意味着它不会作为缺陷报告得到解决。相反,将需要一份正式的变更提案。

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

相关文章:

C++ - 难以理解 easeInOutSine

c++ - 回调和 `std::recursive_mutex` - 有效用例?

c++ - 将不同的 C++ 标准与 GCC 混合

c++ - 在 std::vector 中查找迭代器

java - 随机性水平

c++ - 函数参数中的Qt智能指针

c++ - 删除一个 Char[]

PHP - 多行随机数组

php - 从 MySQL 数据库中选择随机问题; "correct answer"搞砸了

c++ - 检查音乐是否结束,OnStopped?