Channels ▼
RSS

Overloading to Enforce C++ Compile-time Constraints


While reading Chapter One of Matthew Wilson's Imperfect C++ (IC++), I came across those timeless words: "Answers on a postcard, please," as Matthew described an imperfection in a class ancestry compile-time constraint. Confident that the only impossible thing in this world is a young child on e-numbers, I decided that I had to figure out how to solve this problem....

The constraint in question is called must_have_base, which as the name suggests, enforces the fact that one class is derived from another.

The original constraint in IC++, based on a post by Bjarne Stroustrup on comp.lang.c++.moderated and also described as IsDerivedFrom in Herb Sutters' More Exceptional C++, is as follows:

template< typename D <span class="code_comment">// Derived type</span>
        , typename B <span class="code_comment">// Base type</span>
        >
struct must_have_base
{
  ~must_have_base()
  {
    void(*p)(D*, B*) = constraints;
  }
private:
  static void constraints(D* pd, B* pb)
  {
    pb = pd;
  }
};

It takes the address of the constraints method, rather than calling it, to ensure minimal runtime impact, no matter how dense the compiler it's used with. The imperfection in the constraint is that it doesn't prevent the template parameters, D and B, from having the same type.

My solution is to overload the constraints function, with the B and D parameters reversed. If they are of the same type, then the same overload gets defined twice, which is obviously illegal!

The constraints function also gets a name change to cant_be_overloaded_if_same_type, to give more helpful compiler errors in some cases:

 static void cant_be_overloaded_if_same_type(D* pd, B* pb)
  {
    pb = pd;
  }
  static void cant_be_overloaded_if_same_type(B* pb, D* pd)
  {
    pb = pd;
  }

Obviously introducing this change into the extant must_have_base template would run the risk of breaking client code that depends on the old semantics. So it is incorporated into a new constraint, called must_be_derived, which made its debut in the STLSoft libraries in version 1.8.3.

Alas, nothing's ever quite as simple as this: The Borland (C++ Builder 6) compiler takes absolutely no notice of the overload. A bit of poking around revealed that this can be remedied by changing the way that the constraint is enforced in the destructor. If cant_be_overloaded_if_same_type is actually called from the destructor, rather than just taking its address, then all is rosy.

The complete solution is as follows, incorporating the necessary discrimination of functionality for the Borland compiler:

template<   typename D <span class="code_comment">// Derived type</span>
        ,   typename B <span class="code_comment">// Base type</span>
        >
struct must_be_derived
{
public:
    ~must_be_derived()
    {
<i># if defined(STLSOFT_COMPILER_IS_BORLAND)</i>

        cant_be_overloaded_if_same_type(
                static_cast<D*>(0), 
                static_cast<B*>(0)

<i># else /* ? compiler */</i>

        void(*p)(D*, B*) = cant_be_overloaded_if_same_type;

        STLSOFT_SUPPRESS_UNUSED(p); <span class="code_comment">// Suppress compiler 'unused variable' warning</span>

<i># endif /* compiler */</i>
        );
    }

private:
    static void cant_be_overloaded_if_same_type(D* pd, B* pb)
    {
        pb = pd;

        STLSOFT_SUPPRESS_UNUSED(pb); <span class="code_comment">// Suppress compiler 'unused variable' warning</span>
    }
    static void cant_be_overloaded_if_same_type(B* pb, D* pd)
    {                       
        pb = pd;
		
        STLSOFT_SUPPRESS_UNUSED(pb); <span class="code_comment">// Suppress compiler 'unused variable' warning</span>
    }
};

Peter Bannister is a programmer in the UK. He can be contacted at pbannister@asl-electronics.co.uk.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.