Combining template conditions and contracts?

Daniel Kozak via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Feb 29 07:45:33 PST 2016



Dne 29.2.2016 v 15:38 Ozan via Digitalmars-d-learn napsal(a):
>
> T square_root(T)(T x)  if (isBasicType!T) {
> in
> {
>     assert(x >= 0);
> }
> out (result)
> {
>     assert((result * result) <= x && (result+1) * (result+1) > x);
> }
> body
> {
>     return cast(long)std.math.sqrt(cast(real)x);
> } 

import std.traits;
import std.math;

template square_root(T) if (isBasicType!T) {
     auto square_root(T x)
     in
     {
         assert(x >= 0);
     }
     out (result)
     {
         assert((result * result) <= x && (result+1) * (result+1) > x);
     }
     body
     {
         return cast(long)std.math.sqrt(cast(real)x);
     }
}

void main()
{
     import std.stdio: writeln;
     writeln(square_root(2));
}




More information about the Digitalmars-d-learn mailing list