在this comment to another question ,用户 hvd 声明如下:
... although string literals can be passed to
constexpr
functions, and array indexing is allowed on string literals in constant expressions, an indexing operation on aconstexpr
function parameter doesn't qualify as a constant expression.
我没完全理解是什么意思。是不是表示下面代码中的hash_value
变量
#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!");
不能在编译时求值?您能否详细说明引用的评论并判断我是否正确?
最佳答案
我在那条评论中说的是你不能拥有类似的东西
template <int N>
int f();
constexpr int g(int i) {
return f<i>(); // invalid
}
因为尽管 constexpr
函数的结果可以是常量表达式,但在主体内部,它的参数不是。 constexpr
函数可以用常量或非常量参数调用,由调用者决定,C++ 没有任何类型的函数只能被调用有常量参数。
它在您正在阅读的答案中很重要,因为有一个 const char (&str)[N]
函数参数并处理 str[i]
会很有用> 作为函数体内的常量表达式。
这对您的代码无关紧要。该代码没问题。
关于c++ - 可以在编译时对数组进行索引吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25917473/