简体   繁体   English

static_assert可以检查类型是否为向量?

[英]Can static_assert check if a type is a vector?

Can static_assert check if a type is a vector? static_assert可以检查类型是否为向量? IE, an int would raise the assertion, whereas a vector<int> would not. IE, int会引发断言,而vector<int>不会。
I'm thinking of something along the lines of: 我正在考虑以下方面的事情:

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

Yes. 是。 Consider the following meta function: 考虑以下元函数:

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

Simply use that as your expression in static_assert . 只需将其用作static_assert的表达式即可。

的C ++ 0x:

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

A general solution. 一般解决方案。 Given a type, and a template, to check if the type is an instance of the latter: 给定类型和模板,以检查类型是否是后者的实例:

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

With this, then the following will be true: 有了这个,那么以下将是真的:

is_instance_of_a_given_class_template<    vector<int>  ,  vector  > :: value
                    type to check  ~~~~~~~^               ^
        template to check against  ~~~~~~~~~~~~~~~~~~~~~~~/

and therefore you would use: 因此你会使用:

static_assert( is_instance_of_a_given_class_template<T,std::vector>::value
              , "Some error")

Note: If T is const , this won't work directly. 注意:如果Tconst ,则不能直接使用。 So test for something like is_instance_of_a_given_class_template< std::decay_t<T> ,std::vector> instead. 因此,测试类似于is_instance_of_a_given_class_template< std::decay_t<T> ,std::vector>

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

Usage: 用法:

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

Demo . 演示

Note : My (complicated) answer has a limitation that it evaluates to true if if T is publically inherited from vector<> . 注意 :我的(复杂的)答案有一个限制,即如果Tvector<>公开继承,则它的计算结果为true It might result in compiler error if T has private / protected inheritance from vector<> . 如果T具有来自vector<> private / protected继承,则可能导致编译器错误。 Just keeping it for record, that this way should not be used !! 只是保留它的记录,这种方式不应该使用!! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM