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?
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.
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.
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.
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.
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);
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With