我有這個代碼:
#ifdef _DEBUG
#define MY_VERY_SPECIAL_ASSERT(x, ...) assert(x && __VA_ARGS__)
#else
#define MY_VERY_SPECIAL_ASSERT(x, ...)
#endif
這正是它應該做的。但是,為了永遠繼續學習,我試圖遵守constexprcore-cpp 集中的可變引數模板指南。
我嘗試了一些排列,但這一個似乎是最“正確的”
#ifdef _DEBUG
template<typename T>
constexpr void MY_VERY_SPECIAL_ASSERT(T x, const std::string &msg) {
assert(x && msg);
}
#else
template<typename T>
constexpr void MY_VERY_SPECIAL_ASSERT(T x, const std::string &msg) { }
#endif
但當然,它不想編譯。具體來說,“T”和字串沒有邏輯和多載,這是有道理的。你會認為它總是回傳真,對吧?
無論如何,如果有人在這里有任何指示,我很高興了解有關模板的更多資訊。=)
uj5u.com熱心網友回復:
T是一個bool,即它是評估運算式的結果E1與
static_cast<decltype (E1)> (false) != E1;
您收到錯誤是因為std::string沒有隱式轉換為bool.
constexpr void MY_VERY_SPECIAL_ASSERT(T x, const std::string &msg) {
// assert(x && static_cast<bool>(msg)); // won't work
assert(x && msg.empty()); // Should work. The string won't be displayed when an assertion fails, though.
}
但無論如何,這不會像人們想象的那樣。
assert(x && msg);
將始終顯示訊息“斷言失敗:x && msg”。您可以改用它:
assert ( false or !"message" );
#ifndef _DEBUG
# define SPECIAL_ASSERT(...) ()
#else
# define SPECIAL_ASSERT(COND, MSG) (assert(COND or! MSG))
#endif
SPECIAL_ASSERT( 1 == 0, "One isn't zero." );
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/380298.html
下一篇:C 模板的部分特化,沒有代碼重復
