gpt4 book ai didi

c++ - 我们真的需要将范围适配器隐式转换为 bool 值吗?

转载 作者:行者123 更新时间:2023-12-04 04:32:05 25 4
gpt4 key购买 nike

ranges::view_interface 有一个 explicit operator bool() 函数,这使得大多数 C++20 范围适配器能够转换为 bool :
https://godbolt.org/z/ccbPrG51c

static_assert(views::iota(0));
static_assert("hello"sv | views::split(' '));
static_assert(views::single(0) | std::views::transform([](auto) { return 0; }));
虽然这看起来很方便,但我们真的需要这个功能吗?原因是传统的 STL 容器如 std::vector ,或常用的 View ,例如 std::string_view , 不具备转换为 bool 的功能,这似乎有一些不一致之处。调用 .empty() 似乎更直观。或 ranges::empty直接判断一个范围是否为空。
此外,这种隐式转换也可能会引起混淆:
static_assert(!views::empty<int>);
那么,为什么 ranges::view_interface提供这个 operator bool功能?有实际用例吗?
请注意,这可能是一个基于意见的问题,但我想知道 view_interface 背后的哲学。提供 operator bool .

最佳答案

从此blog post作者 Eric Niebler,他的 range-V3 库严重影响了 C++20 的范围

... custom view types can inher[i]t from view_interface to get a host of useful member functions, like .front(), .back(), .empty(), .size(), .operator[], and even an explicit conversion to bool so that view types can be used in if statements

// Boolean conversion operator comes from view_interface:
if ( auto evens = vec | view::filter(is_even) ) {
// yup, we have some evens. Do something.
}

所以这至少是一个将范围 View 转换为 bool 的用例。 .请注意,这是一个显式转换,因此它只发生在执行转换的上下文中,例如通过显式转换,或在 if 中使用它条件,或在 static_assert正如你在你的问题中所说的那样。

正如 Eric 在对此答案的评论中提到的那样,此功能实际上对于所述用例不再有用,大概是因为我们现在将 if-with-initializers 作为语言构造,因此该功能可能会被弃用。

关于c++ - 我们真的需要将范围适配器隐式转换为 bool 值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68806614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com