Workspace 6.21.5
|
Define a constraints base class with a testable value. More...
#include <Workspace/Application/LanguageUtils/classconstraints.h>
Public Types | |
enum | { Is } |
Taken from "Extensible Templates: Via Inheritance or Traits?", Herb Sutter, C/C++ Users Journal, Feb 2002, pp28-38. Note that the merged version called "IsDerivedFrom" in his article does not appear to compile. The workaround for this is to break it up into two separate class templates, one containing the test function machinery and the other to contain just the "Is" enum.
This is a more complicated version of IsDerivedFrom, but serving a slightly different function. It provides the ability to determine at compile time whether a class is derived from another, but it does this through an enumerated data member. This data member can be queried at compile time and used as a template parameter. Hence, it allows you to supply different member functions for a class depending on whether one template parameter is derived from another or not. Consider this:
The second class is a specialization for when the second template parameter is 1. We can now make use of this in a separate class:
The class contains a single data member which is used to access the class that really does the work. Now consider the following:
The impl data member of x1 has the type
which resolves to
and therefore corresponds to class C2.
Similarly, the impl data member of x2 has the type
and we know that "Derived" is a subclass of "Base", so this resolves to
and again corresponds to class C2.
Now look at the impl data member of x3. It has the type
and we know that "Unrelated" is not derived from "Base". Therefore, this resolves to
which corresponds to class C1.
This shows how you can use TestIfDerivedFrom to take different actions depending on whether a class is derived from another or not.
As a final thought, changing impl
to be a typedef instead of a data member may make the process a bit more transparent (this was not part of Sutter's original article):
NOTE: I haven't tested this extension (yet!), but it should work just fine.