检查类是否是模板特化?

2021-12-13 00:00:00 templates c++

如何检查给定类型是否是特定类模板的特化?例如,给定

How can I check if a given type is a specialization of a particular class template? For instance, given

template <class T>
struct A {};

如何检查 CompareT 是否是以下某种类型 *A<*>:

How can I check if CompareT is an A<*> for some type * in the following:

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

int main(){
  compare< A<int> >();
}

例如,这里 A 应该匹配 A<*> 并打印 1.

For example, here A<int> should match A<*> and print 1.

推荐答案

您可以在此处提供要匹配的模板:

Here's one where you can provide the template to be matched against :

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

相关文章