为什么std :: transform和类似函数将'for'循环增量转换为(void)?


77

(void) ++__result以下代码的目的是什么?

std :: transform的实现:

// std::transform
template <class _InputIterator, class _OutputIterator, class _UnaryOperation>
inline _LIBCPP_INLINE_VISIBILITY
_OutputIterator
transform(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _UnaryOperation __op)
{
    for (; __first != __last; ++__first, (void) ++__result)
        *__result = __op(*__first);
    return __result;
}

6
我想知道写风格指南的人是否真的认为如果作者写过代码,这些代码会更清晰static_cast<void>(++__result)吗?
Brian Brian

Answers:


104

有可能过载operator,。强制转换任一操作数以void防止调用任何重载运算符,因为重载运算符无法获取void参数。


27
哇。这对我来说永远不会发生。
Angew不再

11
@Angew有很多这样的东西。要获得更多乐趣,请阅读Microsoft编译器工程师STL撰写的这篇文章
乔治·希利亚德,

7
同样,您会addressof在标准库中看到大量使用或等效项,而不是一元&
TC

4
@JDługosz哈。是的,一个类可以提供,但是不会使用。转换为时,void总是会丢弃该值,而无需查看可用的转换运算符。调用此类运算符的唯一方法是显式expr.operator void()调用。

18
std::who_made_comma_overloadable
MM

6

operator,如果有的话,它避免了重载的调用。因为类型void不能是函数(运算符)的参数。

另一种方法是void()在中间插入:

++__first, void(), ++__result
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.