Enhanced Assertions一文笔记

译文:http://blog.csdn.net/pongba/article/details/19129

 

#include <cassert>
#include <cstdlib>
#include <vector>
#include <iostream>

struct functor
{
    template <typename type>
    functor & operator () (const type & val)
    {
        std::cout << val << std::endl;
        return(*this);
    }
};

struct smart_asserter
{
    smart_asserter() : smart_asserter_a(*this), smart_asserter_b(*this), m_first_value(true)
    {

    }

    ~smart_asserter()
    {
        exit(1);
    }

    smart_asserter & smart_asserter_a;
    smart_asserter & smart_asserter_b;

    smart_asserter & print_error(const char * file, int line, const char * exp)
    {
        std::cout << "smart assert failed: " << exp << ", "
                  << "file " << file << ", "
                  << "line " << line << std::endl;
        return(*this);
    }

    template<typename type>
    smart_asserter & print_context(const char * name, type val)
    {
        if (m_first_value)
        {
            m_first_value = false;
            std::cout << "the context: " << std::endl;
        }
        std::cout << '\t' << name << ':' << val << std::endl;
        return(*this);
    }

    bool m_first_value;
};

#define smart_asserter_a(exp) smart_asserter_op(b, exp)
#define smart_asserter_b(exp) smart_asserter_op(a, exp)
#define smart_asserter_op(n, exp)                                  \
        smart_asserter_a.print_context(#exp, exp).smart_asserter_##n
#define smart_assert(exp)                                                         \
        if (exp)                                                                  \
            ;                                                                     \
        else                                                                      \
            smart_asserter().print_error(__FILE__, __LINE__, #exp).smart_asserter_a

int main(int, char * [])
{
    functor()(1)("hello world!")(2)("hello world!")(3)("hello world!")(4)("hello world!")(5)("hello world!");
//  smart_assert(1 > 2);
    std::vector<int> v0(0);
    std::vector<int> v1(1);
    std::vector<int> v2(2);
    smart_assert(!v0.empty() || !v1.empty() || !v2.empty())(v0.size())(v1.size())(v2.size());
    smart_assert(!v0.empty() && !v1.empty() && !v2.empty())(v0.size())(v1.size())(v2.size());
    std::cout << "never display" << std::endl;
    return(0);
}


发布了172 篇原创文章 · 获赞 10 · 访问量 22万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览