    <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  :: EXPR_TYPE - An Implementation of typeof Using Current
Standard C++</title>
        <link>https://members.accu.org/index.php/articles/359</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 #54 - Apr 2003</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/c157/">54</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+157/">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;EXPR_TYPE - An Implementation of typeof Using Current
Standard C++</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 April 2003 22:57:19 +01:00 or Wed, 02 April 2003 22:57:19 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e21" id="d0e21"></a></h2>
</div>
<p><tt class="literal">typeof</tt> is a much-sought-after facility
that is lacking from current C++; it is the ability to declare a
variable to have the same type as the result of a given expression,
or make a function have the same type as an expression. The general
idea is that <tt class="literal">typeof(some-expression)</tt> would
be usable anywhere a type name could normally be used. This article
describes a way of providing this ability within the realms of
current C++.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e30" id=
"d0e30"></a>Introduction</h2>
</div>
<p>Imagine you're writing a template function that adds its
parameters, such as the following:</p>
<pre class="programlisting">
template&lt;typename T,typename U&gt;
SomeResultType addValues(const T&amp;t,
                         const U&amp;u) {
  return t+u;
}
</pre>
<p>What type should the return value have? Obviously, the ideal
choice would be &quot;the type of <tt class="literal">t</tt>+<tt class=
"literal">u</tt>&quot;, but how can the compiler determine that type?
The rules for the type of an additive expression involving only
builtin types are not trivial - consider pointer arithmetic,
integral type conversions, and integer conversion to floating-point
type - so how do we do it? The Standard C++ Library only deals with
the case where both function parameters have the same type, and
forces the result to be the same type - e.g. <tt class=
"classname">std::plus</tt>, and <tt class=
"classname">std::min</tt>. Another possible solution is to hard
code the rules for this particular operation, as Andrei
Alexandrescu does for <tt class="literal">min</tt> and <tt class=
"literal">max</tt> [<a href="#Alexandrescu">Alexandrescu</a>].</p>
<p>The solution provided by some compilers as an extension, and
widely considered to be a prime candidate for inclusion in the next
version of the C++ standard is the <tt class="literal">typeof</tt>
operator. The idea of <tt class="literal">typeof</tt> is that it
takes an expression, and determines its type at compile time,
without evaluating it, in much the same way as <tt class=
"literal">sizeof</tt> determines the size of the result of an
expression without evaluating it. <tt class="literal">typeof</tt>
could then be used anywhere a normal type name could be used, so we
could declare <tt class="function">addValues</tt> as:</p>
<pre class="programlisting">
template&lt;typename T,typename U&gt;
typeof(T()+U()) addValues(const T&amp;t,
                          const U&amp;u);
</pre>
<p>The function parameters <tt class="literal">t</tt> and
<tt class="literal">u</tt> aren't in scope at the point of
declaration of <tt class="function">addValues</tt>, so we use the
default constructors for the types to generate values to add - the
values used are unimportant, as the expression is never
evaluated<sup>[<a name="d0e90" href="#ftn.d0e90" id=
"d0e90">1</a>]</sup>.</p>
<p>This is good - the return type of <tt class=
"function">addValues</tt> is now correct for all combinations of
types, but we now have the problem that we've used a non-standard
extension, so the code is not portable. One compiler may use the
name <tt class="literal">typeof</tt>, another <tt class=
"literal">__typeof__</tt>, and a third may not provide the
extension at all. We therefore need a portable solution, that uses
only Standard C++.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e105" id="d0e105"></a>Current
Facilities</h2>
</div>
<p>What facilities are there in Standard C++ that we can use?
Firstly, we need a means of obtaining information about an
expression without actually evaluating it. The only Standard
facility for this is <tt class="literal">sizeof</tt><sup>[<a name=
"d0e112" href="#ftn.d0e112" id="d0e112">2</a>]</sup>. We therefore
need a mechanism to ensure that expressions of different types
yield different values for <tt class="literal">sizeof</tt>, so we
can tell them apart, and we need a mechanism for converting a size
into a type.</p>
<p>Another Standard C++ facility we can use to obtain information
about a type is <span class="emphasis"><em>function template
argument type deduction</em></span>. By writing a function template
which has a return type dependent on the argument type, we can
encode information from the argument type into the return type any
way we choose - given:</p>
<pre class="programlisting">
template&lt;typename T&gt;
struct TypeToHelperInfo{};

template&lt;typename T&gt;
TypeToHelperInfo&lt;T&gt; typeOfHelper(const
                                  T&amp; t);
</pre>
<p>we can then write the <tt class=
"classname">TypeToHelperInfo</tt> class template to provide any
necessary information.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e137" id="d0e137"></a>Bringing it
Together</h2>
</div>
<p>Converting a value into a type is easy - just create a class
template with a value template parameter to accept the value which
the type has been assigned. Then, specialize this template for each
value/type combination, as in listing 1 - <tt class=
"literal">Size1</tt> and <tt class="literal">Size2</tt> are
constants, and are the unique size values that relate to
<span class="type">Type1</span> and <span class=
"type">Type2</span>, respectively, rather than <tt class=
"literal">sizeof(Type1)</tt> or <tt class=
"literal">sizeof(Type2)</tt>.</p>
<div class="sidebar">
<pre class="programlisting">
template&lt;std::size_t size&gt;
struct SizeToType {};

template&lt;&gt;
struct SizeToType&lt;Size1&gt; {
  typedef Type1 Type;
};

template&lt;&gt;
struct SizeToType&lt;Size2&gt; {
  typedef Type2 Type;
};
</pre>
<p><span class="bold"><b>Listing 1: Converting a size to a
type</b></span></p>
</div>
<p>Converting a type into a size value is a bit more complex. If we
have an expression <tt class="literal">expr</tt>, of type
<span class="type">T</span>, then <tt class=
"function">typeOfHelper(expr)</tt> is of type <tt class=
"literal">TypeToHelperInfo&lt;T&gt;</tt>, if we use the signature
of <tt class="function">typeOfHelper</tt> from above. We can then
specialize <tt class="classname">TypeToHelperInfo</tt>, so it has a
distinct size for each distinct type. Unfortunately, it is not that
simple - the compiler is free to add padding to <tt class=
"literal">struct</tt>s to ensure they get aligned properly, so we
cannot portably control the size of a <tt class=
"literal">struct</tt>. The only construct in C++ which has a
precisely-defined size is an array, the size of which is the number
of elements multiplied by the size of each element. Given that
<tt class="literal">sizeof(char)==1</tt>, the size of an array of
<span class="type">char</span> is equal to the number of elements
in that array, which is precisely what we need. We can now
specialize <tt class="classname">TypeToHelperInfo</tt> for each
type, to contain an appropriately sized array of <span class=
"type">char</span>, as in listing 2.</p>
<div class="sidebar">
<pre class="programlisting">
template&lt;&gt;
struct TypeToHelperInfo&lt;Type1&gt; {
  char array[Size1];
};

template&lt;&gt;
struct TypeToHelperInfo&lt;Type2&gt; {
  char array[Size2];
};
</pre>
<p><span class="bold"><b>Listing 2: Getting appropriately-sized
arrays for each type</b></span></p>
</div>
<p>We can now simulate <tt class="literal">typeof(expr)</tt> with
<tt class=
"literal">SizeToType&lt;sizeof(typeOfHelper(expr).array)&gt;::Type</tt>.
In templates, we probably need to precede this with <tt class=
"literal">typename</tt>, in case <tt class="literal">expr</tt>
depends on the template parameters. To ease the use, we can define
an <tt class="literal">EXPR_TYPE</tt> macro that does this for
us:</p>
<pre class="programlisting">
#define EXPR_TYPE(expr)
SizeToType&lt;sizeof(
            typeOfHelper(expr).array)&gt;::Type
</pre>
<p>We also need to declare the appropriate specializations of
<tt class="classname">SizeToType</tt> and <tt class=
"classname">TypeToHelperInfo</tt> for each type we wish to detect,
so we define a <tt class="literal">REGISTER_EXPR_TYPE</tt> macro to
assist with this, as in listing 3.</p>
<div class="sidebar">
<pre class="programlisting">
#define REGISTER_EXPR_TYPE(type,value)\
template&lt;&gt;\
struct TypeToHelperInfo&lt;type&gt;{\
  char array[value];\
};\
template&lt;&gt;\
struct SizeToType&lt;value&gt;{\
  typedef type Type;\
};
</pre>
<p><span class="bold"><b>Listing 3: The <tt class=
"literal">REGISTER_EXPR_TYPE</tt> macro.</b></span></p>
</div>
<p>We can then declare the necessary specializations for all the
basic types, and pointers to them, so our users don't have to do
this themselves.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e251" id="d0e251"></a><tt class=
"literal">const</tt> Qualification</h2>
</div>
<p>As it stands, with only the one <tt class=
"function">typeOfHelper</tt> function template, <tt class=
"literal">const</tt> qualifications are lost. This may not be a
problem, as <tt class="literal">const</tt>-qualification doesn't
always have much significance with value types. However, this is a
problem we can overcome<sup>[<a name="d0e267" href="#ftn.d0e267"
id="d0e267">3</a>]</sup> by providing two overloads of <tt class=
"function">typeOfHelper</tt> instead of just the one:</p>
<pre class="programlisting">
template&lt;typename T&gt;
TypeToHelperInfo&lt;T&gt; typeOfHelper(T&amp; t);
template&lt;typename T&gt;
TypeToHelperInfo&lt;const T&gt;
typeOfHelper(const T&amp; t);
</pre>
<p>We can then specialize the class templates for each distinct
cv-qualified type - most easily done by modifying the <tt class=
"literal">REGISTER_EXPR_TYPE</tt> macro to register all four
cv-qualified variants of each type with distinct values. Note that
volatile qualification is automatically picked up correctly,
because <span class="type">T</span> will then be deduced to be
&quot;<tt class="literal">volatile X</tt>&quot; for the appropriate type
<span class="type">X</span>. We only need these distinct overloads
to allow the use of <tt class="literal">EXPR_TYPE</tt> with
expressions that return a non-<tt class="literal">const</tt>
temporary, since with only a single function taking a <span class=
"type">T&amp;</span>, <span class="type">T</span> is deduced to be
the non-<tt class="literal">const</tt> type, and temporaries cannot
bind to non-<tt class="literal">const</tt> references. With both
overloads, the temporary can be bound to the overload that takes
<span class="type">const T&amp;</span>. The result is that
temporaries are deduced to be <tt class=
"literal">const</tt><sup>[<a name="d0e313" href="#ftn.d0e313" id=
"d0e313">4</a>]</sup>.</p>
<p>In the final implementation, all the classes and functions are
in namespace <tt class="literal">ExprType</tt>, to avoid polluting
the global namespace, and the macro definitions have been adjusted
accordingly.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e331" id=
"d0e331"></a>Restrictions</h2>
</div>
<p>The most obvious restriction is that this only works for
expressions that have a type for which we have specialized
<tt class="classname">SizeToType</tt> and <tt class=
"classname">TypeToHelperInfo</tt>. This has the consequence that we
cannot define a specialization for <tt class=
"classname">std::vector</tt> in general; we have to define one
specialization for <tt class=
"classname">std::vector&lt;int&gt;</tt>, and another for <tt class=
"classname">std::vector&lt;double&gt;</tt>. Also, in order to avoid
violating the One Definition Rule, the user must ensure that the
same value is used for the same type in all translation units that
are linked to produce a single program. This includes any libraries
used, so when writing library code that uses <tt class=
"literal">EXPR_TYPE</tt>, it is probably best to put the templates
in a private namespace, to isolate them from the rest of the
program, and avoid the problem.</p>
<p>Also, <tt class="literal">EXPR_TYPE</tt> cannot tell the
difference between an <span class="emphasis"><em>lvalue</em></span>
and an <span class="emphasis"><em>rvalue</em></span>, or between a
reference and a value, except that <span class=
"emphasis"><em>rvalues</em></span> are always <tt class=
"literal">const</tt>, whereas <span class=
"emphasis"><em>lvalues</em></span> may not be - given:</p>
<pre class="programlisting">
int f1();
int&amp; f2();
const int&amp; f3();
int i;
</pre>
<p><tt class="literal">EXPR_TYPE(f2())</tt> and <tt class=
"literal">EXPR_TYPE(i)</tt> are <span class="type">int</span>,
whereas <tt class="literal">EXPR_TYPE(f1())</tt>, <tt class=
"literal">EXPR_TYPE(f3())</tt> and <tt class=
"literal">EXPR_TYPE(25)</tt> are <span class="type">const
int</span>. The reason for this is that the mechanism used for type
deduction - function template argument type deduction - can only
distinguish by cv-qualification, and <span class=
"emphasis"><em>rvalues</em></span> are mapped to <tt class=
"literal">const</tt> references. This means you cannot use
<tt class="literal">EXPR_TYPE</tt> to pass references - you must
explicitly add the <tt class="literal">&amp;</tt> where needed,
though this can be done automatically for non-<tt class=
"literal">const</tt> references. It also means that you may have to
strip the <tt class="literal">const</tt> if the expression results
in an <span class="emphasis"><em>rvalue</em></span>, and you wish
to declare a non-<tt class="literal">const</tt> variable of that
type, using something like <tt class=
"function">boost::remove_const</tt> [<a href="#Boost" title=
"References">Boost</a>].</p>
<p>Finally, <tt class="literal">EXPR_TYPE</tt> cannot be used for
expressions with <tt class="literal">void</tt> type, such as
functions returning <tt class="literal">void</tt>. This is because,
though references to incomplete types are permitted in general,
references to <tt class="literal">void</tt> are explicitly not
permitted.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e442" id="d0e442"></a>Revisiting
the Example</h2>
</div>
<p>To come back to the example from the introduction, we can now
implement our <tt class="literal">addValues</tt> template as:</p>
<pre class="programlisting">
template&lt;typename T,typename U&gt;
typename EXPR_TYPE(T()+U())
addValues(const T&amp; t,const U&amp; u) {
  return t+u;
}
</pre>
<p>However, this still relies on the types <tt class=
"literal">T</tt> and <tt class="literal">U</tt> having default
constructors. We can avoid this restriction by declaring a make
<tt class="literal">T</tt> function template:</p>
<pre class="programlisting">
template&lt;typename T&gt;
T makeT();
</pre>
<p>and then using this template in the parameter for <tt class=
"literal">EXPR_TYPE - EXPR_TYPE(makeT&lt;const
T&amp;&gt;()+makeT&lt;const U&amp;&gt;())</tt>. This is a useful
technique, whenever one is writing such an expression, where all we
want is its type, or size - since the expressions using <tt class=
"literal">makeT</tt> are never evaluated, there is no need to
provide a definition of <tt class="literal">makeT</tt>;
consequently using <tt class="literal">makeT</tt> imposes no
restrictions on the types.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e479" id="d0e479"></a>Further
Examples</h2>
</div>
<p>This technique is useful in any scenario where you wish to
declare an object of a type related to the type of something else,
e.g. declaring a pointer to another variable</p>
<pre class="programlisting">
int i;
EXPR_TYPE(i) * j=&amp;i; // j is &quot;int *&quot;
</pre>
<p>or supporting containers that may or may not declare iterator
and <tt class="literal">const_iterator typedef</tt>s.</p>
<pre class="programlisting">
template&lt;typename Container&gt;
void func(const Container&amp; container) {
  for(typename EXPR_TYPE(container.begin())
      it = container.begin();
      it != container.end(); ++it) {
    // do something
  }
}
</pre>
<p>It can also be used for such things as implementing <tt class=
"literal">min</tt> and <tt class="literal">max</tt> function
templates:</p>
<pre class="programlisting">
template&lt;typename T,typename U&gt;
struct MinHelper {
  typedef typename EXPR_TYPE(
    (makeT&lt;const T&amp;&gt;()&lt;makeT&lt;const U&amp;&gt;())
    ? makeT&lt;const T&amp;&gt;()
    : makeT&lt;const U&amp;&gt;()) Type;
};

template&lt;typename T,typename U&gt;
typename MinHelper&lt;T,U&gt;::Type min(const
T&amp; t,const U&amp; u) {
  return (t&lt;u)?t:u;
}
</pre>
<p>In general, it is of most use in template code, with expressions
where the type depends on the template parameters in a nontrivial
fashion. This allows the writing of more generic templates, without
complex support machinery.</p>
<p>It must be noted, however, that the user must ensure that all
types to be deduced have been registered in advance. The library
can facilitate this by declaring all the builtin types, and some
compound types (e.g. <span class="type">char*</span>, <span class=
"type">const double*</span>, etc.), but class types and more
obscure compound types (such as <span class="type">char
volatile**const*</span>) must be declared explicitly.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e516" id="d0e516"></a>Summary</h2>
</div>
<p>The macros and templates that make up the <tt class=
"literal">EXPR_TYPE</tt> library enable a <tt class=
"literal">typeof</tt>-like mechanism using Standard C++. The only
cost is the maintenance burden placed on the user, to ensure there
is a one-to-one correspondence between types and size-values across
each project, and the only restriction is that it cannot tell the
difference between lvalues and rvalues, and cannot detect void,
though all cv-qualifications are identified.</p>
<p>This powerful mechanism is another tool in the Generic
Programming toolbox, enabling people to write generic code more
easily.</p>
<p>The code presented here will be available with the online
version of the article at : <a href=
"http://cplusplus.anthonyw.cjb.net/articles.html" target=
"_top">http://cplusplus.anthonyw.cjb.net/articles.html</a>.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="Boost" id="Boost"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Alexandrescu" id=
"Alexandrescu"></a>
<p class="bibliomixed">[Alexandrescu] Andrei Alexandrescu,
&quot;Generic&lt;Programming&gt;: Min and Max Redivivus.&quot; C/C++ Users
Journal, 19(4), April 2001. Available online at <span class=
"bibliomisc"><a href="http://www.cuj.com/experts/1904/alexandr.htm"
target=
"_top">http://www.cuj.com/experts/1904/alexandr.htm</a></span>.</p>
</div>
<div class="bibliomixed"><a name="Gibbons" id="Gibbons"></a>
<p class="bibliomixed">[Gibbons] Bill Gibbons, &quot;A Portable &quot;typeof&quot;
operator.&quot; C/C++ Users Journal, 18(11), November 2000.</p>
</div>
<div class="bibliomixed"><a name="Boost" id="Boost"></a>
<p class="bibliomixed">[Boost] The Boost Team. Boost C++ libraries.
See <span class="bibliomisc"><a href="http://www.boost.org" target=
"_top">http://www.boost.org</a></span></p>
</div>
</div>
<div class="footnotes"><br>
<hr class="c2" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e90" href="#d0e90" id=
"ftn.d0e90">1</a>]</sup> There are better ways to generate suitable
expressions, that don't rely on the type having a default
constructor, but they will be dealt with later.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e112" href="#d0e112" id=
"ftn.d0e112">2</a>]</sup> For non-polymorphic types, <tt class=
"literal">typeid</tt> also identifies the type of its operand at
compiletime, without evaluating it, but the return type of
<tt class="literal">typeid</tt> is very little use, as it is not
guaranteed to have the same value for the same type, just an
equivalent value.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e267" href="#d0e267" id=
"ftn.d0e267">3</a>]</sup> for compilers that support partial
ordering of function templates.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e313" href="#d0e313" id=
"ftn.d0e313">4</a>]</sup> Some compilers that don't support partial
ordering of function templates, also allow the binding of
temporaries to non-<tt class="literal">const</tt> references, so we
only need supply a single function, taking <span class=
"type">T&amp;</span>, in which case temporaries are deduced to be
non-<tt class="literal">const</tt>.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
