[英]Variadic template calling assert()
我有这个代码:
#ifdef _DEBUG
#define MY_VERY_SPECIAL_ASSERT(x, ...) assert(x && __VA_ARGS__)
#else
#define MY_VERY_SPECIAL_ASSERT(x, ...)
#endif
这正是它应该做的。 但是,为了永远继续学习,我试图遵守 core-cpp 集中的constexpr
可变参数模板指南。
我尝试了一些排列,但这个似乎是最“正确”的
#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”和字符串没有逻辑和重载,这是有道理的。 你会认为它总是返回 true,对吧?
无论如何,如果有人在这里有任何指示,我很高兴了解有关模板的更多信息。 =)
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." );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.