Boost logo

Boost Users :

From: David Abrahams (dave_at_[hidden])
Date: 2006-10-09 10:08:39


Ian McCulloch <ianmcc_at_[hidden]> writes:

> Gennadiy Rozental wrote:
>>
>> "Stefan Schild" <schilds_at_[hidden]> wrote in message
>> news:eg3r7s$bcb$1_at_sea.gmane.org...
>>> Hi there
>>>
>>> Having a templatized base class B
>>>
>>> template<class T>
>>> class B .....
>>>
>>> is it possible to enforce that a class D can derive from B IF AND ONLY
>>> IF the curiously recurring template pattern is applied, that is
>>>
>>
>> Did you try:
>>
>> template<typename T>
>> class B {
>> BOOST_STATIC_ASSERT( boost::is_base_and_derived<B<T>, T>::value );
>> ....
>> };
>
> This doesn't quite work? At this point, T is incomplete. But, it ought to
> be possible to put this check inside some member function of B;

Right.

> probably the one that casts *this to T& would be the ideal place.
> But then it should be pretty much unnecessary as the static_cast
> will fail if the conversion is not possible.

Right. The assertion (and the cast) will compile anyway even if
certain bad things are done:

        class D1 : public B<D1> ...
        class D2 : public B<D1> ...
        
There's nothing you can do about the 2nd line, because B<D1> is just
as valid there, as far as the compiler is concerned, as it is in the
first line.

I deal with this by saying there's no way to improve on the check that
the static_cast gives you (which is pretty good after all), so you may
as well just stop worrying about it :)

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net