Consider this classic example:
template <typename T, std::size_t N>
constexpr std::size_t arraySize(T (&array)[N]) noexcept { return N; }
Now this works fine, but there is one annoyance, gcc gives a warning:
warning: unused parameter ‘array’ [-Wunused-parameter]
Known solutions:
(void)arr;
to the function, I get error: body of constexpr function ‘...‘ not a return-statement
.arraySize(T (&)[N])
, but I want to name the argument for two reasons:
return sizeof(array)/sizeof(array[0]);
, but this approach is not universal solution, and also I think return N;
is much nicer, definitely easier on the eye.{ (void)array; return N; }
is allowed.How can I get rid of the unused parameter warning nicely, when using C++11?
We allow annotating a function parameter with constexpr with the same meaning as a variable declaration: must be initialized with a constant expression. We add a new keyword, maybe_constexpr , that deduces whether the parameter is known at compile time.
constexpr is a compile time feature, where inline/static are runtime features. The meaning of constexpr is more restricted than static. The meaning is that given a particular input value the return value is always the same, and the copiler ought to be able to work it out completely during compilation.
A constexpr function is one whose return value is computable at compile time when consuming code requires it. Consuming code requires the return value at compile time to initialize a constexpr variable, or to provide a non-type template argument.
constexpr stands for constant expression and is used to specify that a variable or function can be used in a constant expression, an expression that can be evaluated at compile time. The key point of constexpr is that it can be executed at compile time.
Try this. I use this method sometimes
template <typename T, std::size_t N>
constexpr std::size_t arraySize(T (& /*array*/ )[N]) noexcept { return N; }
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