1

Suppose I have a user-defined literal which would be used to calculate the hash code of a char[] at the compiling time:

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

And I could use it like:

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

I just want to keep the hash code in my binary and strip the "Hello" out since it's useless after the hash calculated. How to achieve that?

jayatubi
  • 1,972
  • 1
  • 21
  • 51

2 Answers2

0

No special action is required. The compiler will notice that the value is unused during the optimization phase and strip it out for you.

Make sure you're compiling with -O1 or above and you shouldn't see the "Hello" pop up in your binary.

Tested with GCC 4.9.2.

Wander Nauta
  • 18,832
  • 1
  • 45
  • 62
0
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 use mpq hash.