Home  >  Article  >  Backend Development  >  How to Determine Template Specialization in C ?

How to Determine Template Specialization in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-13 06:25:02711browse

How to Determine Template Specialization in C  ?

Determining Template Specialization

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 should match A<*> and print 1.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn