typeof works with functions

General FreeBASIC programming questions.
Post Reply
shadow008
Posts: 86
Joined: Nov 26, 2013 2:43

typeof works with functions

Post by shadow008 »

For those who didn't know, typeof() can be used with functions, including overloaded and type member functions. I've personally found this valuable to enforce type safety and give more explicit error messages when passing variables to macros that expect a specific type.

typeof() doc page: https://www.freebasic.net/wiki/KeyPgTypeof

Code: Select all

type udt
	dim x as integer
	declare function func overload () as any ptr
	declare function func overload (arg1 as integer) as zstring ptr
end type

function udt.func() as any ptr
	return 0
end function

function udt.func(arg1 as integer) as zstring ptr
	return 0
end function

function test overload () as integer
	return 0
end function

function test overload (arg1 as integer) as string
	return ""
end function

function test overload (arg1 as string) as udt
	return type<udt>(10)
end function

dim a as udt

'The functions are NOT run here, but the arguments are necessary to differentiate overloaded ones!
#print typeof(test())
#print typeof(test(0))
#print typeof(a.func())
#print typeof(a.func(999))

dim b as typeof(test()) = 77
dim c as typeof(test(0)) = "hello"
'etc
fxm
Moderator
Posts: 12181
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: typeof works with functions

Post by fxm »

'Typeof' works exclusively with variables

In your example, 'Typeof' does not strictly speaking work with functions, but more precisely with function returns which are also types of variables.

'Typeof' can also indirectly work with functions (procedures in general), but more precisely with pointer functions which are also types of variables. But on the other hand in case of overload, only the type of the first declared is returned.
Add the following to your example:

Code: Select all

#print typeof(@test())
#print typeof(@udt.func())
and you will get:

Code: Select all

FUNCTION() AS INTEGER
FUNCTION(AS UDT) AS ANY PTR
shadow008
Posts: 86
Joined: Nov 26, 2013 2:43

Re: typeof works with functions

Post by shadow008 »

*Some restrictions apply, see store for details* :D

Good points fxm. And overloaded function types can be specifically obtained via the ProcPtr method.

Code: Select all

#print typeof(ProcPtr(udt.func, function () as any ptr))
#print typeof(ProcPtr(udt.func, function (arg1 as integer) as zstring ptr))
prints out:

Code: Select all

FUNCTION(AS UDT) AS ANY PTR
FUNCTION(AS UDT, AS INTEGER) AS ZSTRING * 8 PTR
fxm
Moderator
Posts: 12181
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: typeof works with functions

Post by fxm »

The only interest of:
Typeof(Procptr(udt.procedurename.....))
is to highlight that a first additional parameter (Byref This As udt)) is passed internally for non-static member procedures, allowing the usage of 'This' in the body of such procedures.
Post Reply