Home > Article > Backend Development > How to Determine Template Specialization in C ?
In C , it is often necessary to ascertain if a given type is a specialization of a particular class template. Consider the example below:
template <class T> struct A {};
How can we determine if CompareT is an A<*> for some type * in the following code?
template<class CompareT> void compare(){ // is this A ? cout << is_same< A<*>, CompareT >::value; // A<*> ???? } int main(){ compare< A<int> >(); }
For instance, here A
Solution:
To achieve this, we can utilize a custom metafunction called is_specialization:
template <class T, template <class...> class Template> struct is_specialization : std::false_type {}; template <template <class...> class Template, class... Args> struct is_specialization<Template<Args...>, Template> : std::true_type {};
This metafunction returns true if T is a specialization of Template and false otherwise. To illustrate its usage:
static_assert(is_specialization<std::vector<int>, std::vector>{}, ""); static_assert(!is_specialization<std::vector<int>, std::list>{}, "");
The above is the detailed content of How to Determine Template Specialization in C ?. For more information, please follow other related articles on the PHP Chinese website!