Home >Backend Development >C++ >Is a Class a Template Specialization in C ?

Is a Class a Template Specialization in C ?

DDD
DDDOriginal
2024-11-13 04:17:02832browse

Is a Class a Template Specialization in C  ?

Is a Class a Template Specialization?

In C , it can be useful to determine if a given type is a specialization of a particular class template. For instance, consider the following code:

template<class T>
struct A {};

template<class CompareT>
void compare() {
    // is this A?
    cout << is_same< A<*> , CompareT >::value << endl; // A<?> ????
}

Given the above code, how can we verify if CompareT is an A<> for some type *?

Solution:

Utilizing the is_specialization template metafunction, you can check if a type is a specialization of a class template. Here's an example:

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 {};

static_assert(is_specialization<std::vector<int>, std::vector>{}, "");
static_assert(!is_specialization<std::vector<int>, std::list>{}, "");

In the above example, is_specialization takes two arguments: T and Template. If T is a specialization of Template, is_specialization is std::true_type. Otherwise, it's std::false_type.

The above is the detailed content of Is a Class a 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