这里的(void)first2 ++有什么意义? [英] What's the point of (void) first2++ here?

查看:175
本文介绍了这里的(void)first2 ++有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个页面的en.cppreference中有可能实施词典比较的例子。这是基本的:

  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);
}

IIRC行像(void)some_argument; 通常用于抑制关于未使用参数的编译器警告。但是在这个函数中,所有参数(包括first2)都使用 - 所以在for语句中写入(void)first2 ++ 是什么意思?如果InputIt1重载 operator,

解决方案

它确保内置的逗号运算符被使用 - 以防万一有用户定义的重载出现意外事件。 void 类型的值永远不能传递给一个函数,所以在这里不能选择这样的重载。



想象一下,如果这个函数存在,会发生什么:

  void operator,(InputIt1 const& InputIt2 const&){launch_missiles (); } 

编辑:这实际上是在相关的 cppreference讨论页面


On this page of en.cppreference there are examples of possible implementation of lexicographical comparison. Here is the basic one:

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);
}

IIRC lines like (void)some_argument; are commonly used to supress compiler warnings about unused parameters. But in this function, all parameters, including first2 are used - so what's the point of writing (void) first2++ in the for statement?

Is it some syntax workaround in case InputIt1 overloads operator,?

解决方案

It ensures that the built-in comma operator is used - just in case there is a user-defined overload that does something unexpected. A value of void type can never be passed to a function, so no such overload could be selected here.

Imagine otherwise what would happen if this function existed:

void operator , (InputIt1 const &, InputIt2 const &) { launch_missiles(); } 

EDIT: This is actually mentioned on the related cppreference discussion page.

这篇关于这里的(void)first2 ++有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆