[英]Why does the std::sentinel_for concept require default constructability?
Why does the new std::sentinel_for
concept require that the sentinel type is default_initializable
(via semiregular
)?为什么新的std::sentinel_for
概念要求哨兵类型是default_initializable
(通过semiregular
)? Doesn't that rule out a large class of useful sentinel types where default construction doesn't make any sense?这不排除大量有用的哨兵类型的 class 默认构造没有任何意义吗?
Example:例子:
//Iterate over a string until given character or '\0' is found
class char_sentinel
{
public:
char_sentinel(char end) :
end_character(end)
{ }
friend bool operator==(const char* lhs, char_sentinel rhs)
{
return (*lhs == '\0') || (*lhs == rhs.end_character);
}
friend bool operator!=(const char* lhs, char_sentinel rhs) { ... }
friend bool operator==(char_sentinel lhs, const char* rhs) { ... }
friend bool operator!=(char_sentinel lhs, const char* rhs) { ... }
private:
char end_character;
};
I know I can add a default constructor which initializes to '\0'
but what if I consider that as misuse of the structure and want to discourage that?我知道我可以添加一个初始化为'\0'
的默认构造函数,但是如果我认为这是对结构的滥用并想阻止它呢?
While this isn't a strict duplicate of this question , my answer there largely still applies.虽然这不是这个问题的严格重复,但我的回答在很大程度上仍然适用。
The Elements of Programming design philosophy of how types behave is that they should be regular
, which EoP defined as:类型行为方式的编程元素设计理念是它们应该是regular
的,EoP 将其定义为:
T's computational basis includes equality, assignment, destructor, default constructor , copy constructor, total ordering (or default total ordering) and underlying type T的计算基础包括相等、赋值、析构函数、默认构造函数、复制构造函数、全序(或默认全序)和底层类型
I think over time this definition has proven to not be the most useful one.我认为随着时间的推移,这个定义已被证明不是最有用的定义。 Equality isn't necessary for a lot of algorithms, hence semiregular
.很多算法都不需要相等,因此semiregular
。 But even default construction isn't necessary in many contexts.但在许多情况下,即使是默认构造也不是必需的。
While we removed the default construction requirement from input iterators, output iterators, and views in P2325R3 , that paper did not touch (or even discuss) sentinels.虽然我们从输入迭代器、output 迭代器和P2325R3中的视图中删除了默认构造要求,但该论文没有涉及(甚至讨论)标记。 The argument for sentinels would largely be the same - that it's not an important requirement, and algorithms don't need it either - but we just didn't pursue weakening sentinel_for
from requiring semiregular
to just requiring copyable
. sentinels 的论点在很大程度上是相同的——它不是一个重要的要求,算法也不需要它——但我们只是没有追求弱化sentinel_for
从需要semiregular
到只需要copyable
。 I'm not sure we had a strong reason to avoid doing so, other than just not being worth it, since sentinels are written less often than iterators anyway.我不确定我们是否有充分的理由避免这样做,除了不值得这样做,因为无论如何编写哨兵的频率都低于迭代器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.