posts - 13, comments - 4, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

Imperfect C++ 读书笔记(一)

Posted on 2008-11-17 22:27 Batiliu 阅读(856) 评论(0)  编辑 收藏 引用 所属分类: 读书笔记

不完美主义实践者的哲学

  • 原则1————C++是卓越的,但并不完美。
  • 原则2————穿上“苦行衣”。
  • 原则3————让编译器成为你的仆从。
  • 原则4————永不言弃,总会有解决方案的。

 

编译期契约:约束

  1. must_have_base

    template<typename D, typename B>
    struct must_have_base
    {
        ~must_have_base()
        {
            void (*p)(D*, B*) = constraints;
        }
    private:
        static void constraints(D* pd, B* pb)
        {
            pb = pd;
        }
    };

  2. must_be_subscriptable

    template<typename T>
    struct must_be_subscriptable
    {
        ~must_be_subscriptable()
        {
            void (*p)(T const &) = constraints;
        }
    private:
        static void constraints(T const &T_is_not_subscriptable)
        {
            sizeof(T_is_not_subscriptable[0]);
        }
    };

  3. must_be_subscriptable_as_decayable_pointer

    template<typename T>
    struct must_be_subscriptable_as_decayable_pointer
    {
        ~must_be_subscriptable_as_decayable_pointer()
        {
            void (*p)(T const &) = constraints;
        }
    private:
        static void constraints(T const &T_is_not_decay_subscriptable)
        {
            sizeof(0[T_is_not_decay_subscriptable]);    // offset[pointer]
        }
    };

  4. must_be_pod

    template<typename T>
    struct must_be_pod
    {
        ~must_be_pod()
        {
            void (*p)() = constraints;
        }
    private:
        static void constraints()
        {
            union
            {
                T T_is_not_POD_type;
            };
        }
    };

  5. must_be_same_size

    template<typename T1, typename T2>
    struct must_be_same_size
    {
        ~must_be_same_size()
        {
            void (*p)() = constraints;
        }
    private:
        static void constraints()
        {
            const int T1_not_same_size_as_T2 = sizeof(T1) == sizeof(T2);
            int i[T1_not_same_size_as_T2];
        }
    };

 

断言

建议使用断言来断言关于代码结构的条件式,而不要断言关于运行期行为的条件式。

静态/编译期断言:

  1. #define STATIC_ASSERT(ex) \
        do { typedef int ai[(ex) ? 1 : 0]; } while(0)
  2. #define STATIC_ASSERT(ex) \
        switch(0) { case 0: case ex: ; }
  3. #define STATIC_ASSERT(ex) \
        struct X { unsigned int v : ex; }

 

域守卫类

template<typename L>
struct lock_traits
{
    static void lock(L &c)
    {
        lock_instance(c);
    }
    static void unlock(L &c)
    {
        unlock_instance(c);
    }
};
 
template<typename L, typename T = lock_traits<L> >
class lock_scope
{
public:
    lock_scope(L &l)
        : m_l(l)
    {
        T::lock(m_l);
    }
    ~lock_scope()
    {
        T::unlock(m_l);
    }
private:
    L &m_l;
};

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理