Skip to content

Instantly share code, notes, and snippets.

@cglosser
Last active December 20, 2016 20:55
Show Gist options
  • Save cglosser/d71e39518c4a415e876e4dc701ec4aea to your computer and use it in GitHub Desktop.
Save cglosser/d71e39518c4a415e876e4dc701ec4aea to your computer and use it in GitHub Desktop.
Typesafe aliases of primitives with zero runtime overhead
module indices
type :: localIdx
integer :: val
end type localIdx
type :: globalIdx
integer :: val
end type globalIdx
contains
function local2global(local) result(global)
type(localIdx), intent(in) :: local
type(globalIdx) :: global
global%val = 2*local%val
end function local2global
function global2local(global) result(local)
type(globalIdx), intent(in) :: global
type(localIdx) :: local
local%val = global%val/2
end function global2local
end module indices
program test
use indices
implicit none
type(localIdx) :: loc
type(globalIdx) :: glob
loc%val = 8
glob = local2global(loc) ! Valid function application
glob = local2global(glob) ! Error: Type mismatch in argument 'local' at (1); passed TYPE(globalidx) to TYPE(localidx)
glob = local2global(8) ! Error: Type mismatch in argument 'local' at (1); passed INTEGER(4) to TYPE(localidx)
write(*,*) loc%val, glob%val
contains
end program safety
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment