Next: , Previous: Arrays, Up: Programming


4.12 Casts

Asymptote implicitly casts int to real, int to pair, real to pair, pair to path, pair to guide, path to guide, guide to path, and real to pen. Implicit casts are also automatically attempted when trying to match function calls with possible function signatures. Implicit casting can be inhibited by declaring individual arguments explicit in the function signature, say to avoid an ambiguous function call in the following example, which outputs 0:

int f(pair a) {return 0;}
int f(explicit real x) {return 1;}

write(f(0));

Other conversions, say real to int or real to string, require an explicit cast:

int i=(int) 2.5;
string s=(string) 2.5;

real[] a={2.5,-3.5};
int[] b=(int []) a;
write(stdout,b);     // Outputs 2,-3

Casting to user-defined types is also possible using operator cast:

struct rpair {
  public real radius;
  public real angle;
}

rpair operator init() {return new rpair;}

pair operator cast(rpair x) {
  return (x.radius*cos(x.angle),x.radius*sin(x.angle));
}

rpair x;
x.radius=1;
x.angle=pi/6;

write(x);            // Outputs (0.866025403784439,0.5)

One must use care when defining new cast operators. Suppose that in some code one wants all integers to represent multiples of 100. To convert them to reals, one would first want to multiply them by 100. However, the straightforward implementation

real operator cast(int x) {return x*100;}
is equivalent to an infinite recursion, since the result x*100 needs itself to be cast from an integer to a real. Instead, we want to use the standard conversion of int to real:
real convert(int x) {return x*100;}
real operator cast(int x)=convert;

Explicit casts are implemented similarly, with operator ecast.