此文版权属于作者智勇
,任何人、媒体或者网站转载、借用都必须征得作者本人同意
编译期契约:约束
- 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
{
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
{
static void constraints(T const & T_is_not_decay_subscriptable)
{
sizeof ( 0 [T_is_not_decay_subscriptable]);
}
}
-
must_be_pod() 必须为 POD 类型
template < typename T >
struct must_be_pod
{
static void constraints()
{
// 利用 POD 类型可以放在 union 中实现这个约束
union{ T T_is_not_POD_type; };
}
};
POD 类型: POD 意思是“plain-old-data”(C++-98:1.8;5),它是C++中的一个重要概念。POD 类型必修满足以下条件:将组成它的一个对象的各字节拷贝到一个字节数组中,然后再将它们重新拷贝回愿先的对象所占的存储区中,此时对象应该仍具有它原来的值。
POD 类型定义: 标量类型、POD 结构类型、POD 联合类型,以上这些类型的数组,以及这些类型以 const/volatile 修饰的版本。
POD 结构:一个聚合体类,其任何非静态成员的类型都不能是如下任意一种:指向成员的指针、非 POD 联合,以及以上这些类型的数组或引用,同时该聚合体类不允许包含用户自定义的拷贝赋值操作符和用户自定义的析够函数。
POD 类型的重要作用: POD 类型允许 C++ 与 C 交互!
- must_be_same_size()
template < typename T >
struct size_of
{
enum { value = sizeof (T); };
};
template <>
struct size_of < void >
{
enum { value = 0 ; };
};
template < typename T1, typename T2 >
struct must_be_same_size
{
static void constraints()
{
const int T1_not_same_size_as_T2 = size_of < T1 > ::value == size_of < T2 > ::value;
int i[T1_not_same_size_as_T2];
}
};

本文是关于C++中编译期契约的读书笔记,重点介绍了一系列的模板结构,如must_have_base、must_be_subscriptable等,用于确保类型满足特定约束,如必须继承自某个基类,必须可按下标方式访问等。此外,还探讨了POD类型的概念及其重要性。

916

被折叠的 条评论
为什么被折叠?



