次のコードは、最大 8 文字の長さの文字列の単純なハッシュのようなものを作成するためのものです。
#include <type_traits>
#include <cstdint>
#include <iostream>
template<std::size_t N, std::size_t n=N>
constexpr typename std::enable_if<N<=9 && n==0,
uint64_t>::type string_hash(const char (&)[N])
{
return 0;
}
template<std::size_t N, std::size_t n=N>
constexpr typename std::enable_if<N<=9 && n!=0,
uint64_t>::type string_hash(const char (&array)[N])
{
return string_hash<N,n-1>(array) | ((array[n-1]&0xffull)<<(8*(n-1)));
}
通常の文字列リテラルと constexpr NULL で終わる文字列の場合、実際には正常に機能します。しかし、私がこのようなことをすると:
constexpr char s2[] = {1,2,3,4,5,6,7,8,9};
std::cout << string_hash(s2) << "\n";
、出力は string の場合と同じになります"\x1\x2\x3\x4\x5\x6\x7\x8"
。static_assert(array[N-1]==0,"Failed");
の定義にa を追加しようとしましたstring_hash
が、コンパイラはそれarray[N-1]
は定数式ではないと言います。次に、パラメーターを宣言しようとしましたconstexpr
が、コンパイラーはパラメーターを宣言できないと言いましたconstexpr
。
次に、このチェックを行うにはどうすればよいですか?