Posted on 2008-11-17 22:27
Batiliu 閱讀(900)
評(píng)論(0) 編輯 收藏 引用 所屬分類:
讀書筆記
不完美主義實(shí)踐者的哲學(xué)
- 原則1————C++是卓越的,但并不完美。
- 原則2————穿上“苦行衣”。
- 原則3————讓編譯器成為你的仆從。
- 原則4————永不言棄,總會(huì)有解決方案的。
編譯期契約:約束
- 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;
}
};
- 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]);
}
};
- 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]
}
};
- 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;
};
}
};
- 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];
}
};
斷言
靜態(tài)/編譯期斷言:
#define STATIC_ASSERT(ex) \
do { typedef int ai[(ex) ? 1 : 0]; } while(0)
#define STATIC_ASSERT(ex) \
switch(0) { case 0: case ex: ; }
#define STATIC_ASSERT(ex) \
struct X { unsigned int v : ex; }
域守衛(wèi)類
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;
};