Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make compile time assertions without C++11

Tags:

c++

templates

In a job interview, I was asked to write a metafunction that determined whether a type was a pointer. This is what I presented:

template <typename T>
struct is_pointer
{ static const bool value = false; }

template <typename T>
struct is_pointer<T *>
{ static const bool value = true; }

Then I was asked to write a meta-assert, that will fail during compile time if my is_pointer function is not doing the right thing.

When I used static_assert, he explicitly told me that I may only use C++98 standard. How can I achieve this?

like image 931
mel- Avatar asked Jul 23 '13 17:07

mel-


People also ask

Does C have Static_assert?

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. In case of failure, an error message is displayed to alert the user.

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.

How does static assert work in C?

Static assertions are used 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. A static assertion is one that is checked at compile time, not run time.

How do you use static assert?

Syntax: static_assert( constant_expression, string_literal ); Parameters: constant_expression: An integral constant expression that can be converted to a Boolean. string_literal: The error message that is displayed when the constant_expression parameter is false.


1 Answers

There are different approaches, a common one trying to typedef an invalid type:

#define static_assert(condition) \
        typedef char assert ## __LINE__ [((condition)?1:-1)]

This can be used in mostly any context and will trip the compiler if the condition is false, since it would try to typedef an invalid type (array of negative number of elements). It can be used in different contexts:

// namespace level:
static_assert(sizeof(int)==4);
struct type {
   // class level:
   static_assert(sizeof(int)==4);
   void f() {
       // function level
       static_assert(sizeof(int)==4);
   }
};
like image 115
David Rodríguez - dribeas Avatar answered Oct 24 '22 01:10

David Rodríguez - dribeas