next up previous
Next: Usage of erase of Up: C++/C Previous: longjmp

Enforcing Compile-time Constraints

Function pointer assignment makes a minimal running overhead. For example to check Driver is a subclass of Base, you can write checking code as
template< typename D // Derived type
          , typename B // Base type
          >
struct must_have_base
{
    ~must_have_base()
        {
            
            void (*p)(D*, B*) = constraints;
        }
private:
    static void constraints(D* pd, B* pb)
        {
            pb = pd;
        }
};


class Base
{};

class D1 : public Base
{};

class D2 
{};


int main() 
{
    must_have_base<D2,Base> foo;
}

Also to test if a type is POD, the code is

template <class T>
struct POD_test
{
    POD_test()
        {
            void (*p) () = do_foo;
        }
private:

    static void  do_foo () 
        {
            union{T t;} u; //T must be a POD type
        }
};


class Foo 
{
public:
    int i;
    int j;
    virtual void foo() 
        {}
};


int main() 
{
    POD_test<Foo> foo;
}
More



Wei Lu 2007-11-06