Skip to main content
GameDev.net gamedev.net
🔒 Locked

restricting template types?

Started by VI2 Aug 23, 2006 at 12:43 AM 3 replies 400+ views
Original Post
VI2
VI2
Hello, I have a question regarding templates. Is it possible to restrict the types used in tempalate classes? IE I want a function: template getMyObject() { ... return (T)myObject }; myObject is stored as a base type, and I want it to be cast to my type T. But I need to make sure that the cast won't fail... Is there a way to limit the arguments into the tempalte type or is this better to do some kind of dynamic_cast checking?
deathkrush
deathkrush
There is no way for the compiler to know the run-time type of myObject. The only way to do this would be to use the dynamic cast operator or implement some sort of type ID system.
deathkrushPS3/Xbox360 Graphics Programmer, Mass Media.Completed Projects: Stuntman Ignition (PS3), Saints Row 2 (PS3), Darksiders(PS3, 360)
MaulingMonkey
MaulingMonkey
It already is limited. That code will fail to compile if you try to use a type that myObject is not convertable to. Any decent compiler will tell you that this is the cause as well, in an error message.
Fruny
Fruny
Note though that using a C cast is a Bad Idea if you're looking for help from the compiler. Use a static_cast, for Eris's sake!
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.