【问题标题】:What's the point of (void) first2++ here? [duplicate](void) first2++ 这里有什么意义? [复制]
【发布时间】:2017-04-16 16:30:35
【问题描述】:

在 en.cppreference 的this 页面上,有一些可能实现词典比较的示例。这是基本的:

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

(void)some_argument; 这样的IIRC 行通常用于抑制关于未使用参数的编译器警告。但是在这个函数中,所有的参数,包括first2都用到了——那么在for语句中写(void) first2++有什么意义呢?

如果 InputIt1 重载 operator,,是否有一些语法解决方法?

【问题讨论】:

    标签: c++ expression


    【解决方案1】:

    它确保使用内置逗号运算符 - 以防万一用户定义的重载执行了意外的操作。 void 类型的值永远不能传递给函数,所以这里不能选择这样的重载。

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

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

    编辑:这个其实在相关的cppreference discussion page里有提到。

    【讨论】:

    • 前几天 MOAB 不就是这样吗?
    猜你喜欢
    • 2014-06-06
    • 1970-01-01
    • 2011-06-30
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    相关资源
    最近更新 更多