Can static_assert check if a type is a vector?
Can static_assert check if a type is a vector? IE, an int
would raise the assertion, whereas a vector<int>
would not.
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
.
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. So test for something like is_instance_of_a_given_class_template< std::decay_t<T> ,std::vector>
instead.
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 !! :)
精彩评论