可以static_assert检查类型是否为vector

Can static_assert check if a type is a vector?

本文关键字:是否 vector 类型 检查 static assert 可以      更新时间:2023-10-16

static_assert可以检查类型是否为vector吗?例如,int会引发断言,而vector<int>不会。
我在想这样写:

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>: %dn", is_vector<int>::value);
   printf("is_vector<vector<int> >: %dn", is_vector<std::vector<int> >::value);
}

简单地使用它作为您在static_assert中的表达式

c++0x:

static_assert(std::is_same<T, std::vector<int>>::value, "Some Error");

通解。给定一个类型和一个模板,检查该类型是否是后者的实例:

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

有了这个,那么下列语句将为真:

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")

注意:如果Tconst,这将不能直接工作。所以测试is_instance_of_a_given_class_template< std::decay_t<T> ,std::vector>之类的东西。

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

用法:

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

演示。

注意:我的(复杂的)答案有一个限制,如果Tvector<>公开继承,它的计算结果为true。如果T从vector<>继承了private/protected,那么可能会导致编译错误。只是为了记录,这种方式不应该使用!!:)

相关文章: