是否可以删除 C++11 用户定义的文字?

Is it possible to make the C++11 User-defined literals to be strip out?

假设我有一个用户定义的文字,用于在编译时计算 char[] 的哈希码:

constexpr unsigned operator "" _hash(const char * pStr, std::size_t length)
{
    // Some code here
}

我可以像这样使用它:

unsigned hash = "Hello"_hash;
std::cout << hash;

我只想将 hash code 保留在我的二进制文件中并删除 "Hello" ,因为在计算哈希后它就没用了。如何实现?

不需要特殊操作。编译器会注意到该值在优化阶段未被使用,并为您将其删除。

确保您使用 -O1 或更高版本进行编译,并且您不会在二进制文件中看到 "Hello" 弹出。

使用 GCC 4.9.2 测试。

constexpr ULONG GenHashTableValue(CONST INT C, USHORT Hi, USHORT Lo, ULONG Seed = 0x00100001) {
  return C == 0 ? (Hi << 0x10) | Lo : (
    Seed = (Seed * 125 + 3) % 0x2aaaab,
            Hi = Seed & 0xffff,
            Seed = (Seed * 125 + 3) % 0x2aaaab,
            Lo = Seed & 0xffff,
            GenHashTableValue(C - 1, Hi, Lo, Seed)
            );
}


constexpr ULONG Index2Count(ULONG N) {
  return GenHashTableValue(N / 0x100 + (N % 0x100) * 5 + 1, 0, 0);
}

constexpr ULONG HashInternal(const void* Data, const SIZE_T Size, HashType HashType, ULONG Seed1 = HashSeed1, ULONG Seed2 = HashSeed2) {
  return Size == 0 ? Seed1
    : (Seed1 = Index2Count((HashType << 8) + ToUpper(Data)) ^ (Seed1 + Seed2),
       Seed2 = ToUpper(Data) + Seed1 + Seed2 + (Seed2 << 5) + 3,
       HashInternal((PUCHAR)Data + 1, Size - 1, HashType, Seed1, Seed2));
}

// utf8 string
constexpr ULONG operator "" _hashO(const char* Str, size_t Size) {
  return HashInternal(Str, Size, HashOffset);
}

vc2015 使用 mpq 哈希。