c++ - How can I check if a type is an instantiation of a given class template? -
this question has answer here:
is possible check type instantiation of particular template?
i have class template 1 of template parameter must either instantiation of particular template, or other type. instance, consider simple definition of typelist:
struct null_type; template <typename head, typename tail> struct typelist { // tail must typelist or null_type typedef head head; typedef tail tail; };
now, make sure type provided tail
template parameter either instantiation of typelist
or null_type
. use partial specialization define template cases, this:
template <typename head, typename tail> struct typelist; // default, not defined template <typename head, typename h, typename t> struct typelist< head, typelist<h,t> > // tail = typelist, ok { typedef head head; typedef typelist<h,t> tail; }; template <typename head> struct typelist< head, null_type > // tail = null_type, ok { typedef head head; typedef null_type tail; };
however, end duplicating code, avoid. ideally, i'd need trait test whether type instantiation of template, use enable_if
or in static assertions:
#include <boost/mpl/or.hpp> #include <type_traits> struct null_type; template <typename head, typename tail> struct typelist { static_assert( boost::mpl::or_< is_instantiation_of< typelist, tail >, std::is_same< tail, null_type > >::value, "tail must typelist or null_type" ); typedef head head; typedef tail tail; };
is such trait (is_instantiation_of
) available in standard library or in boost? is possible write one?
i came following solution, using c++11 variadic templates , simple partial specialization:
#include <type_traits> template < template <typename...> class template, typename t > struct is_instantiation_of : std::false_type {}; template < template <typename...> class template, typename... args > struct is_instantiation_of< template, template<args...> > : std::true_type {};
it adapted c++03 using preprocessor generate versions varying number of template parameters, there maybe simpler way.
Comments
Post a Comment