The Role and Implementation of the Adapter's Base Class
While the traits classes implement a compile-time uniformization of the interface, you can't store an instance of a traits class without knowing the type it is a trait of. This is, in a sense, the same problem as briefly described above, but it elucidates the role of the adapter's base class rather clearly: The adapter's base class exposes the unified interface of the adaptees as a set of abstract functions, which are to be implemented by derived classes which, in turn, are generated with the types to be adapted.
The adapter's base class can, however, also serve a second and perhaps more important role: The role of defining a unified interface contract for all adaptees: by defining a set of pre-and post-conditions which are check directly by the base-class, the base class can make sure that the adaptees really behave as expected and become a very powerful debugging tool once you have to integrate your solution in the final application [8].
Let's take a look at an over-simplified adapter class:
class Adapter { public : virtual ~Adapter(); virtual int get25() const; protected : virtual int get25_() const = 0; };
The implementation of the base class' get2 function simply calls get25_ and checks its post-conditions:
int Adapter::get25() const { int retval(get25_()); assert(retval == 25); // post-condition: we expect get25 to return 25 return retval; }
This enforces a contract that we'll assume to be established: We expect get25 to return 25. This implementation documents that assumption and, if not compiled with NDEBUG, enforces it with a run-time assertion.
As we can't expect derived classes to always be specializations of our own, generic, implementation, we can't implement this check in the derived class and hope it will always be used, so we don't. Hence, our derived class looks like this:
namespace Details { template < typename AdapteeType > class Adapter : public ::Adapter { public : Adapter(AdapteeType * adaptee); protected : int get25_() const; private : AdapteeType * adaptee_; }; template < typename AdapteeType > Adapter< AdapteeType >::Adapter(AdapteeType * adaptee) : adaptee_(adaptee) { /* no-op */ } template < typename AdapteeType > int Adapter< AdapteeType >::get25_() const { return AdapteeTraits< AdapteeType >::get25(adaptee_); } }
If we now take a look at the rest of the implementation of a little test case (from which the code above was taken), we can see that this approach really does work. Here's the traits class:
namespace Details { template < typename AdapteeType > struct AdapteeTraits { static int get25(const AdapteeType * adaptee) { return adaptee->get25(); } }; }
and the adaptee:
struct Adaptee { int get25() const { return 26; } };
which means the following code will fail, as expected:
int main() { Adaptee adaptee; std::auto_ptr>l Adapter > adapter(new Details::Adapter< Adaptee >(&adaptee)); return adapter->get25(); }