Boost logo

Boost Users :

From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2008-03-17 12:26:20


AMDG

Ares Lagae wrote:
> I have a base class template "template <typename T1, typename T2> struct
> base {};" and a derived class "derived" that publicly derives from several
> instantiations from the base class template.
>
> Given a type "T1", is it possible to decide if the class "derived" is
> derived from a base "base<T1,X>" and deduce the unknown type "X"?
>

I couldn't think of a way to do this without typeof.
(At least without enumerating all the possible
first template arguments)

#include <boost/typeof/typeof.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/type_traits/is_same.hpp>

namespace mpl = boost::mpl;

struct no {
    typedef void type;
};

template<class U>
struct wrap {
    no dummy[2];
    typedef U type;
};

template<class T1, class T2>
struct X {};

template<class T, class U1>
struct derives_from_X {
private:
    template<class U2>
    static wrap<U2> test(X<U1, U2>*);
    static no test(...);
    BOOST_TYPEOF_NESTED_TYPEDEF_TPL(nested, test((T*)0));
    typedef typename nested::type result;
public:
    typedef typename result::type template_argument;
    typedef mpl::bool_<sizeof(result) != sizeof(no)> type;
    enum { value = type::value };
};

struct tester : X<int, char>, X<void, double> {};

int main() {
    BOOST_MPL_ASSERT((derives_from_X<tester, int>));
    BOOST_MPL_ASSERT((boost::is_same<derives_from_X<tester,
int>::template_argument, char>));
    BOOST_MPL_ASSERT((derives_from_X<tester, void>));
    BOOST_MPL_ASSERT((boost::is_same<derives_from_X<tester,
void>::template_argument, double>));
}

In Christ,
Steven Watanabe


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