[英]constexpr function not returning constexpr value?
I have the function hash_constexpr
that takes in a const char*
and returns a hash using a novel algorithm. 我有函数hash_constexpr
,它接受const char*
并使用一种新颖的算法返回哈希值。 The hash_constexpr
function should be generating the hash at compile time. hash_constexpr
函数应在编译时生成哈希。
namespace detail
{
template<size_t Count>
inline constexpr size_t countof(const char(&string)[Count])
{
return Count - 1;
}
template<typename T>
struct ascii_hash_t
{
template<typename L>
static constexpr T f(L const& data, T hash, size_t i = 0)
{
return i < countof(data) ? f(data, (hash & (~0u)) ^ (hash << 7) ^ T(data[i]), i + 1) : hash;
}
};
template<typename T, typename L>
inline constexpr T generate_ascii_hash(L const& data)
{
return detail::ascii_hash_t<T>::f(data, 0);
}
};
template<size_t Count>
inline constexpr uint32_t hash_constexpr(const char(&string)[Count])
{
return detail::generate_ascii_hash<uint32_t>(string);
}
My issue is that it appears that the hash_constexpr
function doesn't appear to actually be returning a constexpr
value. 我的问题是,似乎hash_constexpr
函数似乎并未真正返回constexpr
值。 When I invoke it like so: 当我这样调用它时:
constexpr uint32_t asd = hash_constexpr("asdasd");
I get the following error: 我收到以下错误:
Constexpr variable 'asd' must be initialized by a constant expression Constexpr变量“ asd”必须由常量表达式初始化
What am I doing wrong? 我究竟做错了什么?
EDIT #1: 编辑#1:
Note that this call is working correctly: 请注意,此调用工作正常:
constexpr int32_t countof_test = detail::countof("hello");
EDIT #2: 编辑#2:
It appears that this call is working correctly as well: 看来此调用也正常工作:
constexpr int32_t generate_ascii_hash_test = detail::generate_ascii_hash<int32_t>("asd");
The issue is that the function ascii_hash_t::f
, for the specific template instantiation is not a constexpr
. 问题在于,用于特定模板实例化的函数ascii_hash_t::f
不是constexpr
。 This prevents you from performing the operation as a constexpr
. 这样可以防止您以constexpr
执行操作。
See http://ideone.com/heFuFP for an example if it working as you expect. 如果它按预期工作,请参见http://ideone.com/heFuFP以获取示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.