Boost logo

Boost :

Subject: Re: [boost] [type_traits] templated type traits?
From: Vicente J. Botet Escriba (vicente.botet_at_[hidden])
Date: 2012-11-09 19:39:58


Le 10/11/12 00:45, Lorenzo Caminiti a écrit :
> Hi,
>
> Is there a way to inspect if a type is a template instantiaton
> (is_templated) and the type of the instantiated template parameters
> (arg1_type)?
>
> is_templated< std::vector<int> >::value // true
> is_templated< int >::value // false
>
> template_traits< std::vector<int> >::arg1_type // int
>
Hi Lorenzo,

The following works for c++98 and C++11. I left you rework the C++98
part to make it variadic with the help of the preprocessor ;-)

Just before sending I saw that others were quicker than me :(

Hoping this helps,
Vicente

#include <boost/type_traits.hpp>

#if defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)

template <typename T> struct is_templated : boost::false_type{};
template <template <class> class T, typename Arg1>
struct is_templated<T<Arg1> > : boost::true_type {};
template <template <class, class> class T, typename Arg1, typename Arg2>
struct is_templated<T<Arg1,Arg2> > : boost::true_type{};
// ... preprocessor

template <typename T, std::size_t N> struct template_arg {};
template <template <class> class T, typename Arg1>
struct template_arg<T<Arg1>,1> : boost::mpl::identity<Arg1>{};
template <template <class,class> class T, typename Arg1, typename Arg2>
struct template_arg<T<Arg1,Arg2>,1> : boost::mpl::identity<Arg1>{};
template <template <class,class> class T, typename Arg1, typename Arg2>
struct template_arg<T<Arg1,Arg2>,2> : boost::mpl::identity<Arg2>{};
// ... preprocessor

#else

template <typename T> struct is_templated : boost::false_type{};
template <template <class...> class T, typename ...Args>
struct is_templated<T<Args...>> : boost::true_type {};

template <std::size_t N, typename ...Args>
struct nth;
template <typename Arg, typename ...Args>
struct nth<1, Arg, Args...> : boost::mpl::identity<Arg> {};
template <std::size_t N, typename Arg, typename ...Args>
struct nth<N, Arg, Args...> : nth< N-1, Args...> {};

template <typename T, std::size_t N> struct template_arg {};
template <std::size_t N, template <class...> class T, typename ...Args>
struct template_arg<T<Args...>, N>: nth<N, Args...>{};

#endif

// TEST
#include <vector>
#include <boost/static_assert.hpp>

BOOST_STATIC_ASSERT((is_templated<std::vector<int> >::value ));
BOOST_STATIC_ASSERT((is_templated<int>::value == false ));
BOOST_STATIC_ASSERT((boost::is_same<template_arg<std::vector<int>,
1>::type, int>::value));


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk