gpt4 book ai didi

c++ - 可以在编译时对数组进行索引吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:34:28 26 4
gpt4 key购买 nike

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 a constexpr 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com