Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ type trait to check if a type is an instance of template class?

I would like to be able to deduce whether a given type is a template type. I've looked through boost's type trait classes, but can not find is_* traits related to templates: http://www.boost.org/doc/libs/1_52_0/libs/type_traits/doc/html/index.html

What would be even more interesting is if there were ways at compile time to determine properties of the template parameters, such as how many template parameters or if parameters are template template parameters.

like image 955
Kent Knox Avatar asked Oct 16 '25 13:10

Kent Knox


1 Answers

Here's a partial solution:

#include <iostream>
#include <type_traits>

template <typename> struct is_template : std::false_type {};

template <template <typename...> class Tmpl, typename ...Args>
struct is_template<Tmpl<Args...>> : std::true_type {};


template <typename> struct Foo {};

int main()
{
  std::cout << is_template<int>::value << std::endl;
  std::cout << is_template<Foo<char>>::value << std::endl;
}

The problem is that a template can have an arbitrary structure, so it needn't just consist of type parameters. You can't exhaustively enumerate all kinds of template arguments.

However, pursuing this approach for a minute, an arugment counter is readily made:

template <typename> struct nargs : std::integral_constant<unsigned int, 0> { };

template <template <typename...> class Tmpl, typename ...Args>
struct nargs<Tmpl<Args...> : std::integral_constant<unsigned int, sizeof...(Args)> { };
like image 98
Kerrek SB Avatar answered Oct 18 '25 11:10

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!