Home > Mobile >  Check if type is specialization of template for both type and non-type template parameters
Check if type is specialization of template for both type and non-type template parameters

Time:12-22

I've been trying to implement checking to see if a type is a specialization of a specific template. I have seen quite a few answers online, but most of them only work for type parameters.

I found this SO answer that does cover non-type parameters. However, it is undesirable since it wraps them in a struct which is making it very difficult to create a concept for it. It also requires explicitly specifying the non-type template parameters.

I have come up with the following that comes from the answers I've seen online. But for the non-type version, I would have to create a new version for each parameter type (I've used bool... below as an example).

template <template <typename...> typename C, typename   T> struct type_instance_impl : public std::false_type {};
template <template <typename...> typename C, typename...T> struct type_instance_impl<C, C<T...>> : public std::true_type {};
template <template <typename...> typename C, typename   T> concept instance_of_type = type_instance_impl<C, std::decay_t<T>>::value;

template <template <bool    ...> typename C, typename   T> struct non_type_instance_impl : public std::false_type {};
template <template <bool    ...> typename C, bool    ...T> struct non_type_instance_impl<C, C<T...>> : public std::true_type {};
template <template <bool    ...> typename C, typename   T> concept instance_of_non_type = non_type_instance_impl<C, std::decay_t<T>>::value;

Usage:

template <bool...> class bools;

int main(){
  std::cout << instance_of_type<std::complex, std::complex<double>>;
  std::cout << instance_of_non_type<bools, bools<true, false, true>>;

  return 0;
}

Is there a solution that will allow for any non-type parameter (and any amount of parameters)?

I would also like if both the type and non-type version could be combined into a single concept but that isn't necessary.

CodePudding user response:

You don't need to mention every type, you can use auto instead since C 17 to cover all types of non-type parameters. (An exception are reference types which require auto&, and so you can't cover them in one declaration. But they are rarely used.)

However, for your last request you would need to implement every possible combination of type or non-type parameters. There is currently no way in the standard to define a template or template template parameter that allows both a type and a non-type template argument for a given template parameter. (And if you want to also include template template parameters in the set of choices, then you would need to apply all combinations recursively as well.)

I saw a proposal at one point to make this possible, but that was already a long time ago and I haven't noticed anything related to it in the committee papers since.

  • Related