I can then call the template by saying SpawnEntity<entityDerived>() and the compiler's happy, I'm happy, and the program chugs happily along.
But I did realize something that I know I'd never do but I want to know how to prevent for future reference: I can just as easily call SpawnEntity<int>() and piss off either the compiler or the program.
Without having to resort to a template specialization for every funky type, is there a painless way to ensure that the template only gets a type that makes sense to it?
I could do a template specialization for every normal type that I want the template to work on but that completely defeats the purpose and I might as well just have that many normal functions.
Thoughts?
EDIT: The template currently is just printing the class's type via cout and deleting it immediately afterwards since I have no use for the entity right now.

Share this post

Link to post

Share on other sites

But I did realize something that I know I'd never do but I want to know how to prevent for future reference: I can just as easily call SpawnEntity<int>() and piss off either the compiler or the program.

You might give this a read, in particular the section on concepts and modeling.

In short, if the compiler generates an error related to a particular template argument, it is in a sense doing exactly what you want it to do - enforcing the concept that you've established for the type in question.

Now, if you want to impose additional constraints (that is, constraints that are not implied by the code in the body of the 'spawn entity' function), there are ways to do that as well. For example, you could make use of the Boost Type Traits library to ensure that T is in fact derived from EntityBase.