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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With