Sign in to follow this  
caldiar

C++ Templates and Funky Types

Recommended Posts

So, being totally stoked on templates I created a templated function that spawns an entity of any derived type from class entityBase. The code looks like the following: template.h
template<class T> void SpawnEntity(){ 
	T *entity = new T(); 
	entity->broadcast(); 
	delete entity; //simply here for testing purposes
};


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
Your failsafe is the fact that it will not compile, int does not have an implementation of broadcast().

You should be happy you pissed off the compiler, this tells you you have done something dodgy.

Share this post


Link to post
Share on other sites
Quote:
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this