Pointer to a type? (not a type instance...)
BlitzMax Forums/BlitzMax Programming/Pointer to a type? (not a type instance...)
| ||
| I want to pass a pointer of a type as a parameter to a function so that I may access the type's functions from within the called function. For example, I can have:
Type myType
Global x:int
Function GetUniqueNumber:int()
x=x+1
return x
End Function
End Type
'Call the myType.GetUniqueNumber() function
thisVar:int = myType.Add()
That is simple enough.. Now, I want to make a function that can take any type, and execute a certain function within that type... For example: (pseudo)
type myType
global x:int
function GetUniqueNumber:int()
x=x+1
return x
end function
end type
type otherType
global x:int
function GetUniqueNumber:int()
x=x+1
return x
end function
end type
Function callTypeFunction(typePointer var)
return typePointer.GetUniqueNumber()
End Function
if(this)
something=CallTypeFunction(myType)
else
something=CallTypeFunction(otherType)
endif
I know, this is a terrible example, and given this example, there would be much better ways to do this. But it is just to illustrate the concept. Can this be done? |
| ||
| Not possible without a bunch of black magic. Reflection can give you access to methods and fields of an instance, but not functions of a type. The easiest way to do this without some sort of hackery is to pass the pointer to the function (though at that point you should just look for a better way to do what you're trying to do.) |
| ||
you already probably know how to do this but just in case, this can be an alternative(the only way with out the black magic as posted above):
Type base
Function getUniqueNumber:Int()Abstract
End Type
Type myType Extends base
Global x:Int
Function GetUniqueNumber:Int()
x=x+1
Return x
End Function
End Type
Type otherType Extends base
Global x:Int
Function GetUniqueNumber:Int()
x=x+1
Return x
End Function
End Type
Function callTypeFunction:Int(typePointer:base)
Return typePointer.GetUniqueNumber()
End Function
Local type1:myType = New myType
Local type2:otherType = New otherType
If(this)
something:Int=CallTypeFunction(type1)
Else
something:Int=CallTypeFunction(type2)
EndIf
alternatively you can do functions but not types. |
| ||
| Whatever it is you're trying to do, there's probably a better way. Functions in types are no different to functions outside of types. It's just a way of organising your code so functions related to a particular type are bundled together. There's nothing special about them that relates them to a particular type, unlike a method. |
| ||
| Jesse - thanks! While I knew you could extend types and have abstract methods, I didn't know that an instance of a type could be considered also a type of the derived type! (I.e. i didn't know that and instance of MyType could be passed as a parameter as both the MyType type and the Base type) |
| ||
| You are welcome. I guess you finally got the principal of Polymorphism. ;) |