By: Brian Sohr, Principal Software Developer
Previously, I examined different uses of type traits in C++. In this #techtip, I’d like to introduce a very simple, but quite useful technique employing empty classes – tag dispatching. Tag dispatching utilizes empty classes as a mechanism for differentiating between construction behaviors that accept the same data types as arguments.
So, what are tags? Tags are classes which are only that, literally – that is, they are empty classes which contain no data nor behaviors. Using tag classes as constructor arguments is a simple way of writing constructors which accept the same types of data, but are meant to construct the object in differing manners. To illustrate with an example, consider that I may want to write a class A that supports two forms of construction, each accepting a single argument of type std::string. The following is obviously not a possible solution:
Clearly, this is not legal, as the two constructors are indistinguishable. A simple way to achieve the desired behavior is two declare two tag classes, each representing one of the prescribed construction strategies. In so doing, we might end up with the following:
As you would imagine, some simple client code to make use of this might look like:
Now, we obviously have two identifiably different constructor signatures. By virtue of being separate types (and, exactly and only that!), we now have our two constructors with differing behaviors, but accepting the same argument data type.
This is clearly a very simple C++ idiom, but it is extremely clean and readable, and can prove quite useful. Hopefully this toy example has been illustrative, but there are certainly more thorough discussions and demonstrations of tag dispatching that demonstrate more sophisticated applications. One in particular can be found at http://boost.org/community/generic_programming.html#tag_dispatching