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

标签 c++ arrays c++14 constexpr constant-expression

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/

相关文章:

php - 如何将句子转换为单词数组?

c++ - 将非模板基类向下转换为非类型模板子类

C++ 重用调用同一函数的线程 vector

c++ - 在这种情况下,int** 在 C 中意味着什么?

c++ - 还有其他不使用数组来反转字符串的方法吗?

c - 错误检查未正确显示

c - 分段故障

c++ - qmake 自动生成的 Makefile 编译器设置不正确

c++ - Python 和 C++ 代码比较

c++ - 无法在代码块中的 C++ 中找到 float 的机器 epsilon