Is it possible to index arrays at compile time?

In this comment on another question, user hvd stated the following:

... although string literals can be passed to constexpr functions, and array indexing is allowed on string literals in expression constants, the indexing operation on the constexpr function constexpr does not qualify as a constant expression.

I do not quite understand what this means. Does this mean that the hash_value variable in the following code

 #include <cstddef> // Compute the hash of a string literal adding the values of its characters template<std::size_t N> constexpr std::size_t hash_string ( const char (& s)[N] ) noexcept { std::size_t h = 0; // Array indexing happening under the hood for ( const auto c : s ) h += c; return h; } constexpr auto hash_value = hash_string("Hello, world!"); 

can't be evaluated at compile time? Could you tell about the quoted comment and say whether I am right?

+6
source share
2 answers

What I said in this comment was that you cannot have something like

 template <int N> int f(); constexpr int g(int i) { return f<i>(); // invalid } 

because although the result of the constexpr function can be a constant expression, its parameters are absent inside the body. The constexpr function can be called with a constant or with inconsistent arguments, the caller gets the solution, and C ++ does not have any function that can only be called with constant arguments.

This mattered in the answer you read, because it would be useful to have a function argument const char (&str)[N] and consider str[i] as a constant expression inside the body of the function.

It doesn’t matter for the code you have. This code is ok.

+3
source

I went through the relevant sections of both N3337 and N3936, and nothing in any version of the standard prohibits the constexpr sort function

 template<std::size_t N> constexpr std::size_t hash_string ( const char (& s)[N] ) noexcept { return s[0]; } 

And in fact, this compiles both in g ++ and in C ++ 11. I absolutely don’t know where the statement came from that “the indexing operation on the constexpr function constexpr does not qualify as a constant expression”. I cannot find anything in §5.19 [expr.const] that prohibits this.

+2
source

Source: https://habr.com/ru/post/975494/


All Articles