C++0x will introduce 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<double> operator "i"(double d) // cooked form
{
return std::complex<double>(0, d);
}
auto val = 3.14i; // val = complex<double>(0, 3.14)
// binary values
int operator "B"(const char*); // raw form
int answer = 101010B; // answer = 42
// std::string
std::string operator "s"(const char* str) { 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 pounds
At first glance this looks very cool but I'm wondering how applicable it really is, when I tried to think of having the suffixes AD
and BC
create dates I found that it's problematic due to operator order. 1974/01/06AD
would first evaluate 1974/01
(as plain int
s) and only later the 06AD
(to say nothing of August and September having to be written without the 0
for octal reasons). This can be worked around by having the syntax be 1974-1/6AD
so that the operator evaluation order works but it's clunky.
So what my question boils down to is this, do you feel this feature will justify itself? What other literals would you like to define that will make your C++
code more readable?