C++ template-fu: delete_if

I’ve been doing a lot of work with templates lately, for my R* tree implementation (which is morphing into a R* tree and a B tree library) and some things that I’ve been playing around with for Roadnav, especially in regards to serialization.

Heres a neat snippet that I created:

template <bool>
struct delete_if {
	template <typename T>
	static void del(T t) { delete t; }

template <>
struct delete_if
	template <typename T>
	static void del(T t) { /* no-op, doesn't delete */ }

This uses a partial specialization to do the decision portion, and a static member template to eliminate some of the typing (you could get rid of the member template, and you would end up calling delete_if<type, delete_item>::del ).

So what this is intended for is those cases where you are implementing some generic container, and you don’t know whether the type you have is a pointer or not. You *could* use a normal bool as a parameter:

if (delete_it) delete var;

But primary problem with this is that it won’t compile if the type isn’t a pointer. So a sample of something similar to what I’m using it for is something like this:

template < typename T, bool delete_item >
class test {

		// only release the item if the client specifies
		// that they want to

	T val;

Obviously this is just a really simple example of how you can use this. One could also use boost::is_pointer to detect whether the type is a pointer, and pass *that* to delete_if while using a ‘normal’ variable to determine whether the client wants to have the item be deleted or not. I leave that as an exercise for the reader.

Leave a Reply