Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can static_assert check if a type is a vector?

Tags:

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") 
like image 563
小太郎 Avatar asked Aug 05 '11 09:08

小太郎


People also ask

How do you determine a vector type?

To check if type of given vector is character in R, call is. character() function and pass the vector as argument to this function. If the given vector is of type character, then is. character() returns TRUE, or else, it returns FALSE.

What is the behavior if condition provided to Static_assert is evaluated as false?

If the condition is true, the static_assert declaration has no effect. If the condition is false, the assertion fails, the compiler displays the message in string_literal parameter and the compilation fails with an error.

What is Static_assert?

static_assert is a keyword defined in the <assert. h> header. It is available in the C11 version of C. static_assert is used to ensure that a condition is true when the code is compiled. The condition must be a constant expression.


2 Answers

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.

like image 98
Arvid Avatar answered Oct 08 '22 05:10

Arvid


c++0x:

static_assert(std::is_same<T, std::vector<int>>::value, "Some Error"); 
like image 24
rafak Avatar answered Oct 08 '22 05:10

rafak