提升有关逻辑运算的摩擦问题

Boost tribool question about logical operations

本文关键字:摩擦 问题 逻辑运算      更新时间:2023-10-16

最近,我使用了boost::logic::tribool,对我来说有些奇怪。

#include <iostream>
#include "boost/logic/tribool.hpp"

int main()
{
    boost::logic::tribool test = true && boost::logic::indeterminate;
    if(test)
    {
     std::cout << "Executes?" << std::endl;
    }
    if (true && boost::logic::indeterminate)
    {
      std::cout << "Executes 2" << std::endl;
    }
}

打印ExecutesExecutes 2。为什么这些条件是正确的?我完全确定 AND 操作(不确定状态,真(返回不确定状态?

引用 boost.org 关于if中的布尔上下文

"如果 3 态布尔值为真,则返回 true,否则返回 false">

编辑:在评论之后,我正在添加这个。这是我读过的最不直观的代码。

#include <iostream>
#include "boost/logic/tribool.hpp"

int main()
{
    boost::logic::tribool test = boost::logic::tribool(true) && boost::logic::indeterminate;
    if(test)
    {
     std::cout << "This will NOT execute" << std::endl;
    }
    boost::logic::tribool second = true && boost::logic::indeterminate;
    if (second)
    {
      std::cout << "This will execute" << std::endl;
    }
}

编辑2:我需要纠正自己...有人可以解释吗?

#include <iostream>
#include "boost/logic/tribool.hpp"
boost::logic::tribool LOL( )
{
   return    boost::logic::indeterminate;
}
int main()
{
 boost::logic::tribool LOL_RESULT = LOL();
    if (boost::logic::indeterminate)
    {
        std::cout << "IT WILL BE EXECUTED" << std::endl;
    }
    if (LOL_RESULT)
    {
      std::cout << "IT WILL NOT BE EXECUTED"   << std::endl;
    }
}
TEST(junk, tribool)
{
    auto v = boost::logic::indeterminate;
    GTEST_MESSAGE() << typeid(v).name();
}

结果:

[----------] 1 test from junk
[ RUN      ] junk.tribool
[   NOTE   ] bool (__cdecl*)(class boost::logic::tribool,struct boost::logic::detail::indeterminate_t)

boost::logic::indeterminate是一个函数。所以它的结果是真的。

TEST(junk, tribool)
{
    boost::logic::tribool test = true && boost::logic::tribool{ boost::logic::indeterminate_keyword_t() };
    if (test)
    {
        GTEST_MESSAGE() << "Executes?" << std::endl;
    }
    if (true && boost::logic::tribool{ boost::logic::indeterminate_keyword_t() })
    {
        GTEST_MESSAGE() << "Executes 2" << std::endl;
    }
}

结果:

[----------] 1 test from junk
[ RUN      ] junk.tribool
[       OK ] junk.tribool (64970 ms)
[----------] 1 test from junk (68580 ms total)

我认为tribool来自地狱:

"不确定"关键字的类型。这与函数"不确定",以便我们可以识别关键字何时使用。不确定函数具有双重作用。它的第一个角色是作为一个一元函数,用于告知摩擦值是否在"不确定"状态。它的第二个作用是作为关键字表示不确定(就像"真"和"假"表示真假状态(。">