    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Modern C++ Features: User-Defined Literals</title>
        <link>https://members.accu.org/index.php/articles/2318</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #136 - December 2016</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c368/">o136</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-368/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+368/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Modern C++ Features: User-Defined Literals</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 05 December 2016 20:43:14 +00:00 or Mon, 05 December 2016 20:43:14 +00:00</p>
<p><strong>Summary:</strong>&nbsp;User-defined literals were introduced in C++11. Arne Mertz walks us through their use.</p>
<p><strong>Body:</strong>&nbsp;<p>User-defined literals are a convenient feature added in C++11.</p>

<p>C++ always had a number of built-in ways to write literals: pieces of source code that have a specific type and value. They are part of the basic building blocks of the language:</p>

<pre class="programlisting">
  32 043 0x34 // integer literals, type int
  4.27 5E1    // floating point literals, 
              // type double
  'f', '\n'   // character literals, type char
  &quot;foo&quot;       // string literal, type const char[4]
  true, false // boolean literals, type bool
</pre>

<p>These are only the most common ones. There are many more, including some newcomers in the newer standards. Other literals are <code>nullptr</code> and different kinds of prefixes for character and string literals. There also are suffixes we can use to change the type of a built-in numeric literal:</p>

<pre class="programlisting">
  32u         // unsigned int
  043l        // long
  0x34ull     // unsigned long long
  4.27f       // float
  5E1l        // long double</pre>

<h2>Suffixes for user-defined literals</h2>

<p>With C++11, we got the option of defining our own suffixes. They can be applied to integer, floating point, character and string literals of any flavor. The suffixes must be valid identifiers and start with an underscore â€“ those without an underscore are reserved for future standards.</p>

<h3>Using the literals</h3>

<p>User-defined literals are basically normal function calls with a fancy syntax. Iâ€™ll show you in a second how those functions are defined. First, letâ€™s see some examples of how they are used:</p>

<ul>
	<li>user-defined integer literal with suffix <code>_km</code>
		<p><code>45_km</code></p>
	</li>
	
	<li>user-defined floating point literal with suffix <code>_mi</code>
		<p><code>17.8e2_mi</code></p>
	</li>
	
	<li>user-defined character literal with suffix <code>_c</code>
		<p><code>'g'_c</code></p>
	</li>
	
	<li>user-defined character literal (<code>char32_t</code>) with suffix <code>_c</code>
		<p><code>U'%'_c</code></p>
	</li>
	
	<li>user-defined string literal with suffix <code>_score</code>
		<p><code>&quot;under&quot;_score</code></p>
	</li>
	
	<li>user-defined string literal (raw, UTF8) with suffix <code>_stuff</code>
		<p><code>u8R&quot;##(&quot;(weird)&quot;)##&quot;_stuff</code></p>
	</li>
</ul>

<h3>Defining literal operators</h3>

<p>The functions are called literal operators. Given an appropriate class for lengths, the definition of literal operators that match the first two examples above could look like this:</p>

<pre class="programlisting">
  Length operator &quot;&quot; _km(unsigned long long n) {
    return Length{n, Length::KILOMETERS};
  }

  Length operator &quot;&quot;_mi(long double d) {
    return Length{d, Length::MILES};
  }</pre>

<p>More generally, the syntax for the function header is <code>&lt;ReturnType&gt; operator &quot;&quot; &lt;Suffix&gt; (&lt;Parameters&gt;)</code>. The return type can be anything, including <code>void</code>. As you see, there can be whitespace between the <code>&quot;&quot;</code> and the suffix â€“ unless the suffix standing alone would be a reserved identifier or keyword. That means, if we want our suffix to start with a capital letter after the underscore, e.g. <code>_KM</code>, there may be no white space. (Identifiers with underscores followed by capitals are reserved for the standard implementation.)</p>

<p>The allowed parameter lists are constrained: for a user-defined integral or floating point literal, you can already see an example above. The compiler first looks for an operator that takes an <code>unsigned long long</code> or <code>long double</code>, respectively. If such an operator can not be found, there has to be <em>either</em> one taking a <code>char const*</code> <em>or</em> a <code>template&lt;char...&gt;</code> operator taking no parameters.</p>

<p>In the case of the so-called raw literal operator taking a <code>const char</code>, the character sequence constituting the integral or floating point literal is passed as the parameter. In the case of the template, it is passed as the list of template arguments. E.g. for the <code>_mi</code> example above this would instantiate and call:</p>

<pre class="programlisting">
  operator &quot;&quot;_mi&lt;'1', '7', '.', '8', 'e', '2'&gt;()</pre>

<h3>Use cases</h3>

<p>The example with the units above is a pretty common one. You will have noted that both operators return a <code>Length</code>. The class would have an internal conversion for the different units, so with these user defined literals it would be easy to mix the units without crashing your spaceship [<a href="Mertz.xml#[Wikipedia]">Wikipedia</a>]:</p>

<pre class="programlisting">
  auto length = 32_mi + 45.4_km;
  std::cout &lt;&lt; &quot;It's &quot; &lt;&lt; length.miles()
            &lt;&lt; &quot; miles\n&quot;;        //60.21
  std::cout &lt;&lt; &quot;or &quot; &lt;&lt; length.kilometers()
            &lt;&lt; &quot; kilometers.\n&quot;; //96.899
</pre>

<p>The standard library also contains a bunch of these (and yes, they still are called â€˜user-definedâ€™ in standard speak). They are not directly in namespace <code>std</code> but in subnamespaces of <code>std::literals</code>:</p>

<ul>
	<li>From <code>std::literals::complex_literals</code>, the suffixes <code>i</code>, <code>if</code> and <code>il</code> are for the imaginary part of <code>std::complex</code> numbers. So, <code>3.5if</code> is the same as <code>std::complex&lt;float&gt;{0, 3.5f}</code></li>
	
	<li>From <code>std::literals::chrono_literals</code>, the suffixes <code>h</code>, <code>min</code>, <code>s</code>, <code>ms</code>, <code>us</code> and <code>ns</code> create durations in <code>std::chrono</code> for hours, minutes, seconds, milli-, micro- and nanoseconds, respectively.</li>
	
	<li>In <code>std::literals::string_literals</code>, we have the suffix <code>s</code> to finally create a <code>std::string</code> right from a string literal instead of tossing around <code>char const*</code>.</li>
</ul>

<h2>A word of caution</h2>

<p>While user defined literals look very neat, they are not much more than syntactic sugar. There is not much difference between defining and calling a literal operator with <code>&quot;foo&quot;_bar</code> and doing the same with an ordinary function as <code>bar(&quot;foo&quot;)</code>. In theory, we could write literal operators that have side effects and do anything we want, like a normal function.</p>

<p>However, that is not what people would expect from something that does not look like â€˜it does somethingâ€™. Therefore it is best to use user defined literals only as obvious shorthand for the construction of values.</p>

<h2>Playing with other modern C++ features</h2>

<p>A while ago I came across a case where I had to loop over a fixed list of <code>std::string</code>s defined at compile time. In the old days before C++11, the code would have looked like this:</p>

<pre class="programlisting">
  static std::string const strings[] =  
    {&quot;foo&quot;, &quot;bar&quot;, &quot;baz&quot;};
  for (std::string const* pstr = strings;
    pstr != strings+3; ++pstr) {
      process(*pstr);
  }</pre>
  
<p>This is horrible. Dereferencing the pointer and the hard-coded <code>3</code> in the loop condition just donâ€™t seem right. I could have used an <code>std::vector&lt;std::string&gt;</code> here, but that would mean a separate function to prefill and initialize the <code>const</code> vector since there were no lambdas.</p>

<p>Today we have range based <code>for</code>, <code>initializer_list</code>, <code>auto</code> and user-defined literals for strings:</p>

<pre class="programlisting">
  using namespace std::literals::string_literals;
  //...
  for (auto const&amp; str : {&quot;foo&quot;s, &quot;bar&quot;s, &quot;baz&quot;s})
  {
    process(str);
  }</pre>
  
<p>And the code looks just as simple as it should.</p>

<h2>References</h2>

<p class="bibliomixed"><a id="[Wikipedia]"></a>[Wikipedia]  The Mars Climate Orbiter: Cause of Failure <a href="https://en.wikipedia.org/wiki/Mars_Climate_Orbiter#Cause_of_failure">https://en.wikipedia.org/wiki/Mars_Climate_Orbiter#Cause_of_failure</a></p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
