当X为真时断言Y也是如此 - 暗示

时间:2016-02-01 15:07:19

标签: c++

如果Xtrue,那么如何断言Y true也是assert(X && Y && "If X is true then Y should be true too."); 。问题是,如果我写下以下内容:

bool X = false;

将失败,如果{{1}},这也可能是一个有效的案例。

4 个答案:

答案 0 :(得分:5)

逻辑表达式为:assert(!X || (X && Y))

如果您想要包含您的信息,您可以将其包装在括号中:

assert((!X || (X && Y)) && "If X is true then Y should be true too.");

现在,我们可以简化此逻辑,因为我们知道如果!X评估为false(我们正在评估||的右侧),那么我们知道{ {1}}必须为真,所以我们可以进一步简化它:

X

答案 1 :(得分:2)

assert(!X || Y); // If !X is false, then X must be true, so no need to test it.

然后:

constexpr bool a_implies_b( bool a, bool b ) {
  return a?b:true;
}

或者,如果你想玩得开心......

assert(a_implies_b(X, Y) && "If X is true then Y should be true too.");

live example

让你写:

namespace implies_trick {
  struct lhs_t {
    bool v;
    constexpr lhs_t(bool b):v(b) {}
  };
  struct implies_t { constexpr implies_t() {} };
  constexpr implies_t implies = {};
  constexpr lhs_t operator->*( bool a, implies_t ) { return {a}; }
  constexpr bool operator*( lhs_t a, bool b ) { return a.v?b:true; }
}
using implies_trick::implies;

for (bool X:{true, false})
  for (bool Y:{true, false})
    std::cout << X << "->" << Y << " is " << X ->*implies* Y << "\n";

答案 2 :(得分:2)

  

如果断言如果X为真,那么Y也是如此

您所描述的是implicationX → Y

C ++中没有蕴涵运算符。但是,例如使用X → Y等同于¬X ∨ Y的真值表来证明它是微不足道的。我们可以用C ++编写,因为它有否定和OR运算符(析取):

assert(!X || Y);

答案 3 :(得分:0)

与Yakk的答案相似,但语法不同:

#include <iostream>


namespace detail {

    struct when_impl
    {
        constexpr when_impl(bool condition)
        : _cond(condition)
        {}

        constexpr operator bool() const { return _cond; }
        bool _cond;
    };

    struct then_impl
    {
        constexpr then_impl(bool condition)
        : _cond(condition)
        {}

        constexpr operator bool() const { return _cond; }
        bool _cond;
    };

}

constexpr auto when(bool condition)
{
    return detail::when_impl(condition);
}

constexpr auto then(bool condition)
{
    return detail::then_impl(condition);
}

constexpr bool operator,(detail::when_impl when, detail::then_impl then)
{
    if (bool(when)) return bool(then);
    return true;
}

int main()
{
    for (bool X:{true, false})
        for (bool Y:{true, false})
            std::cout << X << "->" << Y << " is " << (when(X), then(Y)) << "\n";

    static_assert((when(true), then(true)), "Y must follow X");
    return 0;
}

预期产出:

1->1 is 1
1->0 is 0
0->1 is 1
0->0 is 1

(注意:构建期间不会触发static_assert)