---
title: "D新闻组里的天才代码"
author: "oldrev"
date: "2008-03-30T21:26:41Z"
tags: []
slug: "d"
draft: false
lastmod: "2008-03-30T21:26:41Z"
id: 177844
url: "https://oldrev.iteye.com/blog/177844"
---

超猛的代码，刚才逛新闻组刚看到的，随便记录一下。


出自：
http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D&article_id=68681



```

import std.stdio;
import std.traits;

//检测整数操作溢出，不过对性能的影响比较大，lazy 关键字的标准运用。
Integral checked(Integral)(lazy Integral dg)
{
     static assert(isIntegral!(Integral));

     Integral result = dg(); //这里才对委托 dg 里的表达式求值
     asm {
         jo overflow;
     }
     return result;

     overflow:
     throw new Exception("Integer overflow occured");
}

int main()
{
     int t = int.max;
     try
     {
         int s = checked(t + 1);
         writefln("Result is %d", s);
     }
     catch(Exception e)
     {
         writefln("Whoops! %s", e.toString());
     }
     return 0;
}
```


连 WB 都服了。