Boost logo

Boost Users :

From: David Abrahams (dave_at_[hidden])
Date: 2005-08-07 08:33:33


sr kumar <srgama_at_[hidden]> writes:

> Hi,
> I am having trouble understanding why the following concept_check,
> which checks an inheritance relationship, doesn't work but the
> BOOST_STATIC_ASSERT does.
>
> Just to make sure that the concept does actually work, the
> LessThanComparableConcept was implemented and then commented out.
>
> Would appreciate getting the missing link in my understanding.
>
> thanks in advance for all help,
> -sr
>
> ------------------------------------------
>
> #include <boost/static_assert.hpp>
> #include <boost/concept_check.hpp>
> #include <boost/type_traits.hpp>
>
> using namespace boost;
>
> template <typename T>
> struct MyConcept {
> void constraints() {
> (bool)(boost::is_base_and_derived<int,T>::value == true);

According to the library docs, the constraints() function is supposed
to "exercise the valid expressions of the concept." The idea is that
if any of the expressions is invalid, instantiating the constraints()
will cause a compilation error. All you've done above is test that

    is_base_and_derived<int,T>::value == true

is syntactically valid and can be converted to bool (using a c-style
cast, no less -- almost anything can be converted that way!). That
expression is valid for any T. Since nothing is derived from int, it
is always false, but the value of the expression isn't what's being
tested here.

If you want to enforce that T is derived from some type X, you need an
expression that will fail to compile if X isn't a base of T. For
example, you could use the STATIC_ASSERT from below in the
constraints() function. However, I recommend

  BOOST_MPL_ASSERT((is_base_and_derived<X,T>));

instead, because you'll get better error messages.

> // (bool)(a<b);
> }
> // T a,b;
> };
>
>
> class X {
> public:
> X() {
> function_requires<MyConcept<X> > ();
> BOOST_STATIC_ASSERT(
> (is_base_and_derived<int,X>::value == true));
> }
> ~X(){}
> // bool operator<(X& rhs) { return (x < rhs.x); }
> int x;
> };
>
>
> int main() { return 0;}

HTH,

-- 
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