Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect and assert virtual inheritance for a specific class?

I have a C++ class that implements reference-counting and I want all users of this class to inherit from this class only virtually so that no object ends up with more than one reference counter.

I'd like some way to assert this requirment either during compile time or at least during runtime.

Is there a way to achieve that?

like image 953
sharptooth Avatar asked Dec 19 '11 09:12

sharptooth


1 Answers

Something like this?

struct RefCounter {
    template <typename T>
    RefCounter(T *) {
        BOOST_STATIC_ASSERT(boost::is_virtual_base_of<RefCounter, T>);
    }
};

struct GoodClass : virtual RefCounter {
    GoodClass() : RefCounter(this) {}
};

struct BadClass : RefCounter {
    BadClass() : RefCounter(this) {}
};

It's a shame about needing to pass this to the constructor, though, to capture the derived type. And of course a wilfully obtuse user could subvert it by passing something other than this.

like image 88
Steve Jessop Avatar answered Oct 14 '22 14:10

Steve Jessop