Search code examples
c++11stripuser-defined-literals

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


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?


Solution

  • 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.