2016-02-01 15 views
1

如何斷言如果Xtrue那麼Y也是true。問題是,如果我寫:在X爲真時斷言Y也爲真 - 暗示

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

會失敗,如果bool X = false;而這可能是一個有效的情況下也。

+6

'X || Y'應該完成這項工作 – tkausl

回答

5

的邏輯表達式爲:assert(!X || (X && Y))

如果要包括你的消息,你可以把它包在括號:

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

現在,我們可以簡化這個邏輯,因爲我們知道,如果!X評價false(我們正在評估的||右側),那麼我們就知道X必須是真實的,所以我們可以進一步簡化它:

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

想想簡化的另一種方法是,如果'Y'是真的,那麼'X'是否爲真並不重要。同樣,如果「X」不是真的,那麼「Y」是否爲真並不重要。 –

2
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."); 

,或者,如果你想有樂趣......

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"; 

live example

,它可以讓你寫:

assert(X ->*implies* Y && "If X is true then Y should be true too."); 
2

如何斷言,如果X是真的,那麼彝族也是如此

什麼你所描述的是implicationX → Y

C++中沒有蘊含運算符。但是,例如使用真值表來證明X → Y相當於¬X ∨ Y是微不足道的。我們可以用C++寫的,因爲它既有否定,或運營商(析取):

assert(!X || Y); 
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構建期間不火)!

+0

爲了定義難以理解的新語法,我們付出了很多努力。 –

+0

@KeithThompson有時我只是沿着我看到的道路前進...... –