|
Boost Users : |
Subject: Re: [Boost-users] Nullary metafunction
From: Joaquin M Lopez Munoz (joaquin_at_[hidden])
Date: 2009-02-03 15:50:45
er <erwann.rogard <at> gmail.com> writes:
>
> Hi All,
>
> I'm looking for template<typename> class F such that
>
> F<T>::type is T::type if it exists, T itself otherwise.
>
> I was hoping apply<T>::type would work, by analogy with the well known
> example apply<std::vector<_>,X>::type, but apparently not.
>
Something like this could do:
#include <boost/mpl/if.hpp>
namespace nested_type_detail{
typedef char yes;
struct no{char x[2];};
template<typename T>
yes helper(T*,typename T::type* =0);
no helper(...);
}
template<typename T>
struct nested_type
{
struct fallback{typedef T type;};
typedef typename boost::mpl::if_c<
sizeof(nested_type_detail::helper(static_cast<T*>(0)))==
sizeof(nested_type_detail::yes),
T,
fallback
>::type::type type;
};
/* testing */
#include <boost/mpl/assert.hpp>
#include <boost/type_traits/is_same.hpp>
struct test1{typedef char type;};
struct test2{typedef char tope;};
typedef char test3;
int main()
{
BOOST_MPL_ASSERT((boost::is_same<nested_type<test1>::type,char>));
BOOST_MPL_ASSERT((boost::is_same<nested_type<test2>::type,test2>));
BOOST_MPL_ASSERT((boost::is_same<nested_type<test3>::type,test3>));
}
JoaquÃn M López Muñoz
Telefónica, Investigación y Desarrollo
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