Home > Backend Development > C++ > body text

How to Determine Template Specialization in C ?

Mary-Kate Olsen
Release: 2024-11-13 06:25:02
Original
714 people have browsed it

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 {};
Copy after login

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> >();
}
Copy after login

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 {};
Copy after login

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>{}, "");
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template