Boost logo

Boost Users :

From: Aleksey Gurtovoy (alexy_at_[hidden])
Date: 2002-05-01 15:27:37


Toon Knapen wrote:
> Inside a templated class, I need to provide two different
> implementations for
> a function based on the compile-time decision
> ::boost::is_convertible< value_type,double >::value.
> How can I do this using MPL ?

1) A simple way:

    template< typename T >
    class my
    {
    public:
        typedef typename T::value_type value_type;

        void foo()
        {
            typedef boost::is_convertible< value_type,double > c;
            do_foo(mpl::bool_c<c::value>());
        }
     
    private:
        void do_foo(mpl::true_c) { /*...*/ }
        void do_foo(mpl::false_c) { /*...*/ }
    };

Andrei has written an article that covers this technique -
http://www.cuj.com/experts/1810/alexandr.htm.

2) A sophisticated one (becomes more relevant when you have several "foo"'s
to handle):

    template< typename T, typename Derived >
    struct foo_impl
    {
        void foo()
        {
            Derived& self = static_cast<Derived&>(*this);
            // ...
        }
    };

    template< typename Derived >
    struct foo_double_impl
    {
        void foo()
        {
            Derived& self = static_cast<Derived&>(*this);
            // ...
        }
    };

    template< typename T >
    class my
        : public mpl::select_if<
              boost::is_convertible< typename T::value_type,double >
            , foo_impl<T, my>
            , foo_double_impl<T>
>::type
    {
        // ...

    private:
        friend class foo_impl<T, my>;
        friend class foo_double_impl<T>;
        // ...
    };

HTH,
Aleksey


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