Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static_assert on inline function gives error

Consider the following case

typedef void (*foo)();
template<foo f>
struct bar {
     static_assert(f!=nullptr,"f == null!");
};

void baz() {}
inline void bax() {  }

bar<baz> ok;
bar<bax> bad; // error: non-constant condition for static assertion

Both baz and bax are accepted as template arguments. It indicates that both are accepted as constants. However, at static_assert they appears to be different (at least in gcc 4.9) - bax is not a constant anymore.

My assumption was that static_assert and template evaluate constantness identically. E.g. either error should be

  • 'bax is not a valid template argument' or
  • static_assert should not raise non-constant condition error.

Am I wrong?

like image 424
hutorny Avatar asked Aug 17 '15 07:08

hutorny


People also ask

Where is Static_assert defined?

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.

Does inline imply static?

@cpplearner Defining any member function inside a class definition makes it implicitly inline . It doens't matter if it's static or not. Instead static member functions means something completely different and is still unrelated to the "inline-ness" of a member function.

When to use static_ assert in c++?

The C++ 11 standard introduced a feature named static_assert() which can be used to test a software assertion at the compile time. Syntax: static_assert( constant_expression, string_literal ); Parameters: constant_expression: An integral constant expression that can be converted to a Boolean.

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.


1 Answers

When a function is inlined, the pointer to the function does not exist. So we can not compare it with nullptr.

Whether a function is eventually inlined or not, depends on the compiler. inline keyword does not guarantee that.

like image 73
Alexander Lobov Avatar answered Oct 17 '22 08:10

Alexander Lobov