C++ 为什么(void)在for循环中的两个逗号分隔语句之间
以下代码来自上的C++ 为什么(void)在for循环中的两个逗号分隔语句之间,c++,c++11,for-loop,void,comma,C++,C++11,For Loop,Void,Comma,以下代码来自上的std::lexicographical\u compare的实现示例: 模板 bool词典比较(InputIt1 first1,InputIt1 last1, InputIt2 first2,InputIt2 last2) { 对于(;(first1!=last1)和&(first2!=last2);++first1,(void)++first2){ if(*first1
std::lexicographical\u compare
的实现示例:
模板
bool词典比较(InputIt1 first1,InputIt1 last1,
InputIt2 first2,InputIt2 last2)
{
对于(;(first1!=last1)和&(first2!=last2);++first1,(void)++first2){
if(*first1<*first2)返回true;
如果(*first2<*first1)返回false;
}
返回(first1==last1)&(first2!=last2);
}
为什么循环中有一个
(void)
,不放在那里会有什么后果?如果InputIt1
类型的前缀增量运算符返回的值类型重载了逗号运算符,则表达式++first1,++first2
可以调用它,因此,将++first2
的结果强制转换为void
可以确保不会调用重载的逗号运算符,因为重载的逗号运算符不能接受void
作为参数。这似乎是一个偏执的实现者,因为他们不知道所处理类型的确切细节有
您可能知道也可能不知道,运算符,
可以重载类型。因此,在使用诸如++first1、++first2
之类的语句时,甚至仅使用first1、first2
时,可能会出现意外后果
(void)
强制转换被放置在那里,因此任何重载的操作符都不能生效,因为操作符不能对不完整的void
类型进行操作。有人计划在++first1
之前添加(void)
,因为++first1,(void)++first2
仍然可以实例化某个操作符,
在某个地方声明,这可能仍然会造成麻烦。@cpplooner Someone,嗯?疯狂的语言规范已经确认。有人见过重载的合法用法吗?@Passer By::boost::huh?它是如何使用的?刚刚签出boost::assign@PasserBy使用名称空间boost::assign;向量v;/*…*/v+=1,2,3,4,5,6,7,8,9将值附加到@Passer-By的v
末尾的code>
template<class InputIt1, class InputIt2>
bool lexicographical_compare(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2)
{
for ( ; (first1 != last1) && (first2 != last2); ++first1, (void) ++first2 ) {
if (*first1 < *first2) return true;
if (*first2 < *first1) return false;
}
return (first1 == last1) && (first2 != last2);
}