可以在编译时对数组进行索引吗
Can arrays be indexed at compile time?
在对另一个问题的评论中,用户hvd陈述了以下内容:
尽管可以将字符串文本传递给CCD_ 1函数,并且允许对常量中的字符串文字进行数组索引表达式,对
constexpr
函数参数的索引操作不符合常量表达式的条件。
我没有完全理解这是什么意思。这是否意味着以下代码中的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]
视为函数体中的常量表达式,这会很有用。
这对你的代码来说并不重要。那个代码很好。
我浏览了N3337和N3936的相关章节,在这两个版本的标准中都没有禁止类型的constexpr
函数
template<std::size_t N> constexpr std::size_t
hash_string
( const char (& s)[N] )
noexcept
{
return s[0];
}
事实上,它在C++和clang中都以C++11模式编译。我完全不知道"对constexpr
函数参数的索引操作不符合常量表达式"的说法是从哪里来的。我在§5.19[expr.const]中找不到任何禁止这样做的内容。
相关文章:
- 特征获取索引数组,其中向量中的值为真(不需要循环)
- 是否可以使用字符串或字符索引数组
- 为什么在使用字符索引数组时会出现这种不同的行为
- 在具有重复索引的索引数组处更改 ArrayFire 数组
- 使用索引数组订购 ArrayFire Array 的最佳方式
- C++ 中结构的动态索引数组
- 1索引数组上的qsort()正在扰乱索引
- C++ 索引数组打印和删除字符串名称 数组打印
- 字符串下标超出范围.我不知道如何使用字符索引数组,所以我使用了(无符号整数),但它不起作用
- openGL drawElements - 一个额外的三角形,使用索引数组
- 具有索引数组的地形(高度贴图)LOD
- 通过创建索引数组进行 C++ 排序
- OpenGL:两个顶点数组 + 两个索引数组
- 将索引数组排序为主数组
- 自动循环跳过某些索引数组
- 为静态强制转换的索引数组生成数组
- 重载枚举索引数组的std::get
- 使用c++中的第二个索引数组对数组进行排序
- 给定的零索引数组 &该数组的均衡索引
- CUDA:重新索引数组