Can static_assert check if a type is a vector?

给你一囗甜甜゛ 提交于 2020-01-02 00:12:17

问题


Can static_assert check if a type is a vector? IE, an int would raise the assertion, whereas a vector<int> would not.
I'm thinking of something along the lines of:

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

回答1:


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.




回答2:


c++0x:

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



回答3:


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. So test for something like is_instance_of_a_given_class_template< std::decay_t<T> ,std::vector> instead.




回答4:


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<>. It might result in compiler error if T has private/protected inheritance from vector<>. Just keeping it for record, that this way should not be used !! :)



来源:https://stackoverflow.com/questions/6953969/can-static-assert-check-if-a-type-is-a-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!