VS14 CTP – User-defined literals

User-defined literals is a C++ 11 feature that’s been implemented in the VS 14 CTP. Some of the standard headers have already been updated to define user defined literals. Example, <string> has an s-suffix for string literals. So you can do the following now, and both lines of code are identical.

auto s1 = "hello"s;
auto s2 = string("hello");

The definition in <string> (as of the CTP) looks like this:

inline string operator "" s(const char *_Str, size_t _Len)
  { // construct literal from [_Str, _Str + _Len)
  return (string(_Str, _Len));
  }

Here’s a common example used to demonstrate how you’d use user defined literals in your code. Consider the following Weight class.

struct Weight
{
  WeightUnitType Unit;

  double Value;

  double Lb;

  Weight(WeightUnitType unitType, double value)
  {
    Value = value;
    Unit = unitType;

    if (Unit == WeightUnitType::Lb)
    {
      Lb = value;
    }
    else
    {
      Lb = 2.2 * value;
    }
  }
};

Now here’s how you’d define _kg and _lb literal operators for this class.

Weight operator "" _kg(long double value)
{ 
  return (Weight(WeightUnitType::Kg, static_cast<double>(value)));
}

Weight operator "" _lb(long double value)
{
  return (Weight(WeightUnitType::Lb, static_cast<double>(value)));
}

And here’s how you’d use them in your code.

auto w1 = 10.0_kg;
auto w2 = 22.0_lb;

cout << (w1.Lb == w2.Lb) << endl; // outputs 1 (true)

Be aware that your literals will need to have a _ as the start of the suffix. Else, you’ll just get an error:

literal suffix identifiers that do not start 
with an underscore are reserved

I would assume that <string> does not need an underscore as it’s permitted as a special case.

Advertisements

One thought on “VS14 CTP – User-defined literals

  1. Thank you for sharing your knowledge. I’m a new learner in this field. I guess I should should do my homework and pull an all-nighter in order to be an expert on this.

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