《Imperfect C++》中的一个约束的例子,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;
}
};
这里将他补全,使得他避免类型相同,或者赋值给void*情况。
新增2个特化,程序清单如下:
template <typename T>
struct must_have_base<T,T>
{
~must_have_base()
{
const int not_the_same_type = 0;
int i[not_the_same_type];
}
};
template <typename T>
struct must_have_base<T,void>
{
~must_have_base()
{
const int not_the_void = 0;
int i[not_the_void];
}
};
在vc上,这些代码可以做到在编译期约束的。