Skip to content

User defined literals

October 27, 2011

User defined literals were added to GCC earlier today, as of SVN revision 180532. Essentially, it allows you to parse literals however you want in a way that looks nice. We don’t have to wrap everything up as a string argument to a function, we can just write a literal. Here is an example:

#include <gmpxx.h>
#include <iostream>
#include <cmath>
 
mpz_class operator"" _mpz(const char* s, size_t)
{
  return mpz_class(s);
}
 
mpz_class operator"" _mpz(const char* s)
{
  return mpz_class(s);
}
 
long double operator"" _degrees(long double d)
{
  return d / 180 * M_PI;
}
 
int main()
{
  std::cout << 42_mpz << std::endl;
  std::cout << "1234567890123456"_mpz << std::endl;
  std::cout << 360_degrees << std::endl;
  std::cout << 180_degrees << std::endl;
  std::cout << 90_degrees << std::endl;
  std::cout << std::sin(90_degrees) << std::endl;
}


Note that I am using _ in the literal name. It works without, but gcc warns me that using literals without underscores is reserved for future extensions. I think it’s more readable anyway.

There is one last nifty feature of this. If the literals are either integer or float, the parameters can be given as template arguments. With that we can do something like this:

template <char...>
std::string operator"" _names()
{
  return "hello :)";
}
 
template <>
std::string operator"" _names<'6', '6', '6'>()
{
  return "The Devil >:)";
}
 
template <>
std::string operator"" _names<'4', '2'>()
{
  return "The meaning of life";
}
 
int main()
{
  std::cout << 666_names << std::endl;
  std::cout << 42_names << std::endl;
  std::cout << 5_names << std::endl;
}

The output from this will be
The Devil >:)
The meaning of life
hello :)

Since these arguments are template parameters, and templates are Turing complete we can build whatever we want at compile time. More on that later.

Advertisements

From → Language

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: