【发布时间】:2014-11-13 01:52:00
【问题描述】:
在this comment to another question,用户 hvd 声明如下:
...虽然字符串文字可以传递给
constexpr函数, 并且允许对常量中的字符串文字进行数组索引 表达式,对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!");
无法在编译时进行评估?您能否详细说明引用的评论并判断我是否正确?
【问题讨论】:
-
我在 C++14 标准中没有看到任何禁止这一点的内容。您的代码在 clang 中编译得很好。
-
很多编译器都做这种优化吗?这似乎非常激进。
-
@T.C.是的,它在 Clang 上也可以编译并且对我来说也很好。但是,特别是因为我不知道汇编,我想确保在编译时对其进行评估。
-
@Kalrish 如果你写
constexpr auto foo = ...;,它必须在编译时进行评估。 -
昨天Computing length of a C string at compile time. Is this really a constexpr? ...分配给
constexp变量的一些相关问题将在编译时进行评估,我也没有看到您的代码有任何问题。跨度>
标签: c++ arrays c++14 constexpr constant-expression