繁体   English   中英

为什么将三个变量与 == 一起比较的结果为假?

[英]Why comparing three variables together with == evaluates to false?

以下程序的 output 是“它们不相等”,但我希望“它们相等”,因为三个比较变量( xyz )相等。 为什么?

#include <iostream>

int main()
{
    int y, x, z;
    y = 3;
    x = 3;
    z = 3;

    if (x == y == z)
    {
        std::cout << "they are equal\n";
    }
    else
    {
        std::cout << "they are not equal\n";
    }
}

这是因为表达式和类型的评估方式。

让我们评估最左边的==

x == y ...

这评估为真。 让我们重写表达式:

//  x == y
if (true   == z) {
    // ...
}

true是 boolean 值。 boolean 值不能直接与int进行比较。 必须进行从 boolean 到 integer 的转换,结果为1 (是的, true == 1 )。 让我们将表达式重写为其等效值:

//  true
if (1    == z) {
    //    ^--- that's false
}

但是z不等于1 那个表达是假的!

相反,您应该分开两个 boolean 表达式:

if (x == y && y == z) {
    // ...
}

而现在一些实用的C++17应用。 不需要 SFINAE。

//----------------------------------
// constexpr lambda requires C++17
auto eq3 = [] (auto v1, auto v2, auto v3) constexpr -> bool
{
    return ( v1 == v2 ) && ( v2 == v3 );
};

用法简单但完全编译时间

constexpr auto same_ = eq3(42,42,42);
std::bool_constant< eq3(42,42,42) > twins_ ;

对于比较一个完整的值序列,概念是相同的,执行要复杂一些。

template<typename ... T>
constexpr bool all_equal ( const T & ... args_ )  
{
    if ((sizeof...( args_) ) < 2) return true;
    // for non recursive version
    const auto il_ = { args_ ... };
    // compare them all to the first
    auto first_ = *(il_.begin()) ;
    // assumption
    bool rezult_{ true }; 
    for ( auto && elem_ : il_) {
        // yes I know, first cycle compares first_ to itself ...
        rezult_ = rezult_ && ( first_ == elem_ );
        // short circuit-ing
        if (!rezult_) break;
    }
    return rezult_; 
};

“只是”一个 function,编译时,再次没有可变参数模板技巧。

    bool_constant< all_equal(42,42,42,42,42,42,42) > same_ ;
    cout << endl << boolalpha <<  same_() ;

    bool_constant< all_equal(42,43,44,45,46,47) > not_same_ ;
    cout << endl << boolalpha <<  not_same_() ;

强制性魔杖盒在这里

ps:有些可预测的all_equal不能使用最新的 CL(也称为 MSVC 或 Visual Studio)进行编译。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM