Author Topic: Operator overloading and casting  (Read 1466 times)

0 Members and 1 Guest are viewing this topic.

Charles Pegge

  • Guest
Operator overloading and casting
« on: February 27, 2018, 05:56:59 AM »
Using 2d and 3d vectors to demonstrate how to create operator-sets for them and use them together in expressions with converters (casts). Commonly used functions like str can be overloaded for these UDTs using the same mechanism.

Code: [Select]
'2018-02-23 T 09:14:27
'generic operations for type conversion etc

  type vector2d float x,y
  '
  type vector3d float x,y,z
  '
  macro cvt_op (a,b,  le,cd)
  ==========================
  int le=sizeof a
  if le>sizeof b then le=sizeof b
  copy @a,@b,le
  '#if match typeof(a), typeof(b)
  '  'identical type
  '#elseif typecodeof(a)<0x100 and typecodeof(b)<0x100
  '  'primitive types
  '#else
  '  #if leftmatch "vector",typeof a
  '    cd=1
  '  #endif
  '  #if leftmatch "vector",typeof b
  '    cd or=16
  '  #endif
  '  if cd=17 then copy @a.@b,le
  '#endif
  end macro
  '
  macro str_op string (a,b)
  =========================
  #if match typeof(b), "vector2d"
    a=b.x ", " b.y
  #elseif match typeof(b), "vector3d"
    a=b.x ", " b.y ", " b.z
  #else
    a= "str "#b#""
  #endif
  end macro

  macro vector2d_op
  =================
  '
  macro ."load"(acc,a)
    acc.x=a.x
    acc.y=a.y
  end macro
  '
  macro ."+"(acc,a)
    acc.x+=a.x
    acc.y+=a.y
  end macro
  '
  macro ."save"(a,acc)
    a.x=acc.x
    a.y=acc.y
  end macro

  end macro

  macro vector3d_op
  =================
  '
  macro ."load"(acc,a)
    acc.x=a.x
    acc.y=a.y
    acc.z=a.z
  end macro
  '
  macro ."+"(acc,a)
    acc.x+=a.x
    acc.y+=a.y
    acc.z+=a.z
  end macro
  '
  macro ."save"(a,acc)
    a.x=acc.x
    a.y=acc.y
    a.z=acc.z
  end macro

  end macro
'
'TESTS
'=====
'
int a
float v
vector2d v2d
vector3d v3d
'
'print str(v3d)
'str(v2d)
'v2d=cvt(a)
'v3d+=cvt(a)
'v3d= v3d+cvt(a)
'v3d=v3d+v3d
'v2d=v2d+cvt(v2d)
'v2d=v2d+cvt(v3d)
'v2d=v2d+cvt(v2d)+cvt(v3d)+cvt(4)+cvt(4.5)

https://github.com/Charles-Pegge/OxygenBasic/blob/master/OxygenProgress.zip

jack

  • Guest
Re: Operator overloading and casting
« Reply #1 on: February 27, 2018, 10:13:44 AM »
thank you Charles Pegge :)