Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mark a constexpr function's parameter unused?

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:

  • Doesn't work: If I add the classic (void)arr; to the function, I get error: body of constexpr function ‘...‘ not a return-statement.
  • Unsatisfactory: I can have arraySize(T (&)[N]), but I want to name the argument for two reasons:
    1. It makes compiler error message more understandable.
    2. More subjectively, I think it makes the code clearer, especially to those who don't live and breathe that syntax.
  • Not good: In this particular example, I could also 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.
  • Good but not always possible: switch to using C++14 and compiler which supports it fully. Then constexpr function body like { (void)array; return N; } is allowed.

How can I get rid of the unused parameter warning nicely, when using C++11?

like image 202
hyde Avatar asked Oct 25 '15 07:10

hyde


People also ask

Can a function parameter be constexpr?

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.

Is constexpr implicitly static?

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.

Are constexpr evaluated at compile time?

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.

What is the point of constexpr?

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.


1 Answers

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; }
like image 176
fnc12 Avatar answered Oct 06 '22 21:10

fnc12