工大后院

 找回密码
 加入后院

扫一扫,访问微社区

QQ登录

只需一步,快速开始

搜索
查看: 1771|回复: 0

[C++] About Design by Constrains

[复制链接]
发表于 2008-5-3 22:39 | 显示全部楼层 |阅读模式
在看 Imperfect C++ ,
第一章说的是约束,契约。

想知道在实际的C++编程中,会不会用到这样的办法来控制程序员的行为
(能过编译器来把关,而不仅仅在文档里写出要求由程序员自觉遵守):

比如,要求两个类的size相等
  1. template <  typename T1 , typename T2 >
  2. struct must_be_same_size{
  3.     ~must_be_same_size(){
  4.         //强制让编译器检查,但constrains函数不会被调用。
  5.         void(*p)()=constrains;
  6.     }
  7.   private:
  8.      void static constrains(){
  9.          const int T1_not_same_size_as_T2=  ( sizeof(T1)==sizeof(T2) );
  10.          int  i[ T1_not_same_size_as_T2 ];//如果T1_not_same_size_as_T2为0则出现编译错误。从而实现约束
  11.       }
  12. }
复制代码

评分

1

查看全部评分

您需要登录后才可以回帖 登录 | 加入后院

本版积分规则

QQ|Archiver|手机版|小黑屋|广告业务Q|工大后院 ( 粤ICP备10013660号 )

GMT+8, 2025-5-14 11:29

Powered by Discuz! X3.5

Copyright © 2001-2024 Tencent Cloud.

快速回复 返回顶部 返回列表