C++ 静态断言是否可以检查类型是否为向量?

C++ 静态断言是否可以检查类型是否为向量?,c++,c++11,static-assert,C++,C++11,Static Assert,静态断言是否可以检查类型是否为向量?也就是说,int将引发断言,而vector则不会引发断言。 我在想一些大致如下的事情: static_assert(decltype(T) == std::vector, "Some error") 对。考虑下面的元函数: #include <stdio.h> #include <vector> template <class N> struct is_vector { static const int value =

静态断言是否可以检查类型是否为向量?也就是说,
int
将引发断言,而
vector
则不会引发断言。
我在想一些大致如下的事情:

static_assert(decltype(T) == std::vector, "Some error")

对。考虑下面的元函数:

#include <stdio.h>
#include <vector>

template <class N>
struct is_vector { static const int value = 0; };

template <class N, class A>
struct is_vector<std::vector<N, A> > { static const int value = 1; };

int main()
{
   printf("is_vector<int>: %d\n", is_vector<int>::value);
   printf("is_vector<vector<int> >: %d\n", is_vector<std::vector<int> >::value);
}
#包括
#包括
模板
结构是_向量{static const int value=0;};
模板
结构是_向量{static const int value=1;};
int main()
{
printf(“is_向量:%d\n”,is_向量::值);
printf(“is_向量:%d\n”,is_向量::值);
}
只需在
static\u assert
Yes中使用该表达式即可

template<typename T>
struct isVector
{
  typedef char (&yes)[2];
  template<typename U>
  static yes check(std::vector<U>*);
  static char check(...);

  static const bool value = (sizeof(check((T*)0)) == sizeof(yes));
};
模板
结构向量
{
typedef字符(&yes)[2];
模板
静态是检查(标准::向量*);
静态字符检查(…);
静态常量布尔值=(sizeof(check((T*)0))==sizeof(yes));
};
用法:

isVector<vector<int> >::value;
isVector<int>::value;
isVector::value;
isVector::值;

注意:如果
T
是从
vector
公开继承的,则我(复杂)的答案有一个限制,即它的计算结果为
true
。如果T具有从
向量
继承的
私有
/
保护
继承,则可能导致编译器错误。只是记录在案,不要用这种方式!!:)

c++0x:

static_assert(std::is_same<T, std::vector<int>>::value, "Some Error");
static_断言(std::is_same::value,“某些错误”);

通用解决方案。给定类型和模板,以检查该类型是否为后者的实例:

template<typename T, template<typename...> class Tmpl>
struct is_instance_of_a_given_class_template : std:: false_type {};
template<template<typename...> class Tmpl, typename ...Args>
struct is_instance_of_a_given_class_template< Tmpl<Args...>, Tmpl > : std:: true_type {};
模板
struct是给定类模板的实例:std::false\u type{};
模板
struct是给定类模板:std::true\u type{}的实例;
有了这一点,以下内容将成为事实:

is_instance_of_a_given_class_template<    vector<int>  ,  vector  > :: value
                    type to check  ~~~~~~~^               ^
        template to check against  ~~~~~~~~~~~~~~~~~~~~~~~/
是给定类模板的实例::值
键入以检查~~~~~~^^
要检查的模板~~~~~~~~~~~~~~~~~~~~~~~/
因此,您将使用:

static_assert( is_instance_of_a_given_class_template<T,std::vector>::value
              , "Some error")
static\u assert(是给定的\u类\u模板的\u实例\u::值
“一些错误”)

注意:如果
T
const
,则此操作不会直接起作用。所以像
这样的测试是给定类模板的实例,std::vector>

请记住,它的分配器类型可能与默认值不同。@sharptooth:或带有
boost::true\u type
false\u type的typedef
@GMan:有办法解决这种情况吗?@sharptooth:分配器只是另一个模板参数。因此,第一个专门化可能类似于
template struct is_vector{…}
,它应该覆盖所有情况,包括分配器。@Steve Jessop:或继承自
std::true_type
std::false_type
。这就是为什么它们被包含在c++0x中。但是如果向量是一个char向量,我也想接受它和int向量一起使用呢?难道不是
std::is_same
a
c++11
吗?@shrevardhan“c++0x”的意思与“c++11”相同吗@小太郎: 您必须检查
std::is_same
。当然,如果
T
不是向量,它甚至可能没有
值\u type