Over the past year, UDLs have started to become available in some popular C++ compilers, including gcc 4.7 and Clang 3.1. As people are adopting those compilers in real code and starting to be ablel to use this feature, a natural question is how useful they are and how to use them:
What new capabilities do user-defined literals add to C++?
C++11 introduces user-defined literals which will allow the introduction of new literal syntax based on existing literals (int, hex, string, float) so that any type will be able to have a literal presentation.
Examples:
// imaginary numbers std::complex<long double> operator "" _i(long double d) // cooked form { return std::complex<long double>(0, d); } auto val = 3.14_i; // val = complex<long double>(0, 3.14) // binary values int operator "" _B(const char*); // raw form int answer = 101010_B; // answer = 42 // std::string std::string operator "" _s(const char* str, size_t /*length*/) { return std::string(str); } auto hi = "hello"_s + " world"; // + works, "hello"_s is a string not a pointer // units assert(1_kg == 2.2_lb); // give or take 0.00462262 poundsAt first glance this looks very cool but I'm wondering how applicable it really is, [...] do you feel this feature will justify itself? What other literals would you like to define that will make your C++ code more readable?
Add a Comment
Comments are closed.