在编译时确定类型是否为STL容器 [英] Determine if a type is an STL container at compile time

查看:146
本文介绍了在编译时确定类型是否为STL容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个模板,它将在编译时确定类型是否为stl容器。



我有以下代码: / p>

  struct is_cont {}; 
struct not_cont {};

template< typename T>
struct is_cont {typedef not_cont result_t; };

但我不知道如何为 std创建必要的专业化: :vector< T,Alloc> ;, deque< T,Alloc> ;, set< T,Alloc,Comp> etc ...

首先,定义您的主要模板,它将有一个在默认情况下为false的成员:

  template< typename T> 
struct is_cont {
static const bool value = false;
};

然后您将为您的容器类型定义具有值为true的部分特化:

  template< typename T,typename Alloc> 
struct is_cont< std :: vector< T,Alloc> > {
static const bool value = true;
};

然后对于要检查的类型X,使用

  if(is_cont< X> :: value){...} 


I would like to write a template that will determine if a type is an stl container at compile time.

I've got the following bit of code:

  struct is_cont{};
  struct not_cont{};

  template <typename T>
  struct is_cont { typedef not_cont result_t; };

but I'm not sure how to create the necessary specializations for std::vector<T,Alloc>, deque<T,Alloc>, set<T,Alloc,Comp> etc...

解决方案

First, you define your primary template, which will have a member which is false in the default case:

template <typename T>
struct is_cont {
  static const bool value = false;
};

Then you will define partial specializations for your container types which have a value of true instead:

template <typename T,typename Alloc>
struct is_cont<std::vector<T,Alloc> > {
  static const bool value = true;
};

Then for a type X that you want to check, use it like

if (is_cont<X>::value) { ... } 

这篇关于在编译时确定类型是否为STL容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆