阵列可以在编译时被编入索引? [英] Can arrays be indexed at compile time?

查看:212
本文介绍了阵列可以在编译时被编入索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在<一个href=\"http://stackoverflow.com/questions/25576363/check-whether-equal-string-literals-are-stored-at-the-same-address#comment39958822_25577498\">this另一个问题评论,用户HVD声明如下:

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

...虽然字符串可以传递给 constexpr 的功能,
  和数组索引被允许在常量​​字符串字面量
  前pressions,在 constexpr 函数参数的索引操作
  没有资格作为一个恒定的前pression。

... 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.

我没有完全理解什么意思。这是否意味着在以下code中的 HASH_VALUE 变量

I didn't fully understand what was meant. Does it 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!");

不能在编译时进行评估?你能否详细说明所引用注释,告诉我们,如果我是正确的?

cannot be evaluated at compile time? Could you elaborate on the quoted comment and tell if I am right?

推荐答案

我在评论中说的是,你不能有像

What I was saying in that comment was that you cannot have something like

template <int N>
int f();

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

,因为虽然一个 constexpr 函数的结果可以是一个恒定的前pression,身体内部,它的参数都没有。 A constexpr 函数可以用常数或与非恒定的参数来调用,调用者得到确定,和C ++没有任何形式的功能,可以的的被称为恒定参数。

because although the result of a constexpr function can be a constant expression, inside the body, its parameters aren't. A constexpr function may be called with constant or with non-constant arguments, the caller gets to decide, and C++ doesn't have any sort of function that can only be called with constant arguments.

这要紧在你读,因为这将是有益的有为const char答案(安培; STR)[N] 函数参数,和治疗海峡[I] 作为函数体内恒定的前pression。

It mattered in the answer you were reading because it would have been useful to have a const char (&str)[N] function argument, and treat str[i] as a constant expression inside the function body.

这不要紧为code你已经有了。这code是罚款。

This doesn't matter for the code you've got. That code is fine.

这篇关于阵列可以在编译时被编入索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆