Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I static_assert on types?

Tags:

c++

Inspired by one of the comments on this question I wanted to write this in my code because I may have made wrong assumptions that would need investigating if I ever port the code to a platform where the two types are not the same.

static_assert(typeid(float) == typeid(GLfloat), "GLfloat is unexpected type");

However that does not compile because error: call to non-constexpr function ‘bool std::type_info::operator==(const std::type_info&) const’

I can however write this :-

static_assert(sizeof(float) == sizeof(GLfloat), "GLfloat is unexpected size");

And it works just as expected. That will most likely be sufficient to give me a compile time error if my assumptions are wrong on a new platform but I was wondering if there was any way to achieve what I really wanted - to compare the actual types?

like image 541
jcoder Avatar asked Nov 07 '13 00:11

jcoder


People also ask

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.

What is the difference between assert () and static_assert ()? Select one?

Answer: Static_assert is evaluated at compile time as against the assert () statement that is evaluated at run time. Static_assert has been incorporated in C++ from C++11 onwards. It takes the conditional expression and a message to be displayed as arguments.

When to use static_ assert?

Use static_assert for assertions that should not occur on a usual basis.

Why we use static_ assert in c++?

Static assertions are a way to check if a condition is true when the code is compiled. If it isn't, the compiler is required to issue an error message and stop the compiling process. The condition that needs to be checked is a constant expression.


1 Answers

Use traits:

#include <type_traits>

static_assert(std::is_same<float, GLfloat>::value, "GLfloat is not float");
like image 137
Kerrek SB Avatar answered Sep 19 '22 02:09

Kerrek SB