Boost logo

Boost Users :

From: Roman Perepelitsa (roman.perepelitsa_at_[hidden])
Date: 2007-07-23 02:42:44


Martin Ecker <martin.ecker <at> gmx.net> writes:
>
> Hi,
>
> Is there a way, using SFINAE tricks and potentially the techniques
> used in the Boost Concept Check Library, to detect at compile-time if
> a type T supports a certain expression? In my case, I'm interested if
> T supports operator ==. So I'm basically looking for a compile-time
> predicate so that this compiles:
>
> struct my_struct { int i; };
> struct my_struct2 { int i; };
> bool operator == (my_struct2 const&, my_struct2 const&) const;
>
> BOOST_STATIC_ASSERT((supports_comparison_operator<int>::value));
> BOOST_STATIC_ASSERT((!supports_comparison_operator<my_struct>::value));
> BOOST_STATIC_ASSERT((supports_comparison_operator<my_struct2>::value));

This implementation is based on boost/detail/is_incrementable.hpp.

#include <boost/type_traits/remove_cv.hpp>
#include <boost/static_assert.hpp>

namespace detail {

    struct tag {};
    
    struct any { template <class T> any(T const&); };

    tag operator==(any const&, any const&);

    tag operator,(tag,int);
    
    char (& check(tag))[2];

    template <class T>
    char check(T const&);

    template <class T>
    struct impl
    {
        static typename boost::remove_cv<T>::type& x;

        static const bool value =
        sizeof(check(((x == x),0))) == 1;
    };
}

template <class T>
struct is_eq_comparable : detail::impl<T> {};

struct A{};

int main()
{
    BOOST_STATIC_ASSERT(is_eq_comparable<int>::value);
    BOOST_STATIC_ASSERT(!is_eq_comparable<A>::value);
}

Roman Perepelitsa.


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