Avoiding unused variables warnings when using assert() in a Release build

前端 未结 16 1831
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 09:10

Sometimes a local variable is used for the sole purpose of checking it in an assert(), like so -

int Result = Func();
assert( Result == 1 );
<
16条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-05 09:44

    // Value is always computed.  We also call assert(value) if assertions are
    // enabled.  Value is discarded either way.  You do not get a warning either
    // way.  This is useful when (a) a function has a side effect (b) the function
    // returns true on success, and (c) failure seems unlikely, but we still want
    // to check sometimes.
    template < class T >
    void assertTrue(T const &value)
    {
      assert(value);
    }
    
    template < class T >
    void assertFalse(T const &value)
    { 
      assert(!value);
    }
    

提交回复
热议问题