Type Erasure

In their book on C++ template metaprogramming, Dave Abrahams and Aleksey Gurtovoy define type erasure as &“the process of turning a wide variety of types with a common interface into one type with that same interface.” Perhaps the most widely known and used example of type erasure is boost::function. boost::function is a class template that takes one template argument, a function type. Choosing a function type amounts to choosing a return type and a list of argument types for a function. Suppose we instantiate boost::function as follows:

boost::function < int (int) > foo;

The variable foo can now hold anything that’s callable with an int as its only argument, and whose return type is convertible to int. This could be a function pointer, a user-defined functor, the result of a boost::bind, or what have you not. Clearly, this matches the above definition of type erasure.

The relevance of this in the context of object-oriented programming is that an interface can now say to the client programmer: “I need you to give me something that’s callable as specified by this here function type. What it really is, I don’t care. You can give me different things at run time. Also, you can change your client code so it gives me something other than it did before, and you won’t have to recompile me.” Or, referring to a return value rather than an argument, an interface could say: “I’ll give you something that’s callable as specified by this here function type. What it really is, you won’t know. It could change at run time. I might also change it at compile time, but don’t worry, you won’t have to recompile because of that.”

continue…