<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.5"/> <title>Eigen: The template and typename keywords in C++</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="eigendoxy.css" rel="stylesheet" type="text/css"> <!-- --> <script type="text/javascript" src="eigen_navtree_hacks.js"></script> <!-- <script type="text/javascript"> --> <!-- </script> --> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <!-- <a name="top"></a> --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="Eigen_Silly_Professor_64x64.png"/></td> <td style="padding-left: 0.5em;"> <div id="projectname"><a href="http://eigen.tuxfamily.org">Eigen</a>  <span id="projectnumber">3.2.0</span> </div> </td> <td> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.5 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('TopicTemplateKeyword.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Namespaces</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark"> </span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark"> </span>Enumerator</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(8)"><span class="SelectionMark"> </span>Friends</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(9)"><span class="SelectionMark"> </span>Groups</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(10)"><span class="SelectionMark"> </span>Pages</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="headertitle"> <div class="title">The template and typename keywords in C++ </div> </div> </div><!--header--> <div class="contents"> <div class="textblock"><p>There are two uses for the <code>template</code> and <code>typename</code> keywords in C++. One of them is fairly well known amongst programmers: to define templates. The other use is more obscure: to specify that an expression refers to a template function or a type. This regularly trips up programmers that use the Eigen library, often leading to error messages from the compiler that are difficult to understand.</p> <h1><a class="anchor" id="TopicTemplateKeywordToDefineTemplates"></a> Using the template and typename keywords to define templates</h1> <p>The <code>template</code> and <code>typename</code> keywords are routinely used to define templates. This is not the topic of this page as we assume that the reader is aware of this (otherwise consult a C++ book). The following example should illustrate this use of the <code>template</code> keyword.</p> <div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div> <div class="line"><span class="keywordtype">bool</span> isPositive(T x)</div> <div class="line">{</div> <div class="line"> <span class="keywordflow">return</span> x > 0;</div> <div class="line">}</div> </div><!-- fragment --><p>We could just as well have written <code>template <class T></code>; the keywords <code>typename</code> and <code>class</code> have the same meaning in this context.</p> <h1><a class="anchor" id="TopicTemplateKeywordExample"></a> An example showing the second use of the template keyword</h1> <p>Let us illustrate the second use of the <code>template</code> keyword with an example. Suppose we want to write a function which copies all entries in the upper triangular part of a matrix into another matrix, while keeping the lower triangular part unchanged. A straightforward implementation would be as follows:</p> <table class="example"> <tr> <th>Example:</th><th>Output: </th></tr> <tr> <td><div class="fragment"><div class="line"><span class="preprocessor">#include <Eigen/Dense></span></div> <div class="line"><span class="preprocessor">#include <iostream></span></div> <div class="line"></div> <div class="line"><span class="keyword">using namespace </span>Eigen;</div> <div class="line"></div> <div class="line"><span class="keywordtype">void</span> copyUpperTriangularPart(<a class="code" href="classEigen_1_1Matrix.html">MatrixXf</a>& dst, <span class="keyword">const</span> <a class="code" href="classEigen_1_1Matrix.html">MatrixXf</a>& src)</div> <div class="line">{</div> <div class="line"> dst.triangularView<<a class="code" href="group__enums.html#ggab59c1bec446b10af208f977a871d910bae70afef0d3ff7aca74e17e85ff6c9f2e">Upper</a>>() = src.triangularView<<a class="code" href="group__enums.html#ggab59c1bec446b10af208f977a871d910bae70afef0d3ff7aca74e17e85ff6c9f2e">Upper</a>>();</div> <div class="line">}</div> <div class="line"></div> <div class="line"><span class="keywordtype">int</span> main()</div> <div class="line">{</div> <div class="line"> <a class="code" href="classEigen_1_1Matrix.html">MatrixXf</a> m1 = <a class="code" href="classEigen_1_1DenseBase.html#a2278addf9a3c977d40322571a0df8ac9">MatrixXf::Ones</a>(4,4);</div> <div class="line"> <a class="code" href="classEigen_1_1Matrix.html">MatrixXf</a> m2 = <a class="code" href="classEigen_1_1DenseBase.html#a8e759dafdd9ecc446d397b7f5435f60a">MatrixXf::Random</a>(4,4);</div> <div class="line"> std::cout << <span class="stringliteral">"m2 before copy:"</span> << std::endl;</div> <div class="line"> std::cout << m2 << std::endl << std::endl;</div> <div class="line"> copyUpperTriangularPart(m2, m1);</div> <div class="line"> std::cout << <span class="stringliteral">"m2 after copy:"</span> << std::endl;</div> <div class="line"> std::cout << m2 << std::endl << std::endl;</div> <div class="line">}</div> </div><!-- fragment --> </td><td><pre class="fragment">m2 before copy: 0.68 0.823 -0.444 -0.27 -0.211 -0.605 0.108 0.0268 0.566 -0.33 -0.0452 0.904 0.597 0.536 0.258 0.832 m2 after copy: 1 1 1 1 -0.211 1 1 1 0.566 -0.33 1 1 0.597 0.536 0.258 1 </pre> </td></tr> </table> <p>That works fine, but it is not very flexible. First, it only works with dynamic-size matrices of single-precision floats; the function <code>copyUpperTriangularPart()</code> does not accept static-size matrices or matrices with double-precision numbers. Second, if you use an expression such as <code>mat.topLeftCorner(3,3)</code> as the parameter <code>src</code>, then this is copied into a temporary variable of type MatrixXf; this copy can be avoided.</p> <p>As explained in <a class="el" href="TopicFunctionTakingEigenTypes.html">Writing Functions Taking Eigen Types as Parameters</a>, both issues can be resolved by making <code>copyUpperTriangularPart()</code> accept any object of type <a class="el" href="classEigen_1_1MatrixBase.html" title="Base class for all dense matrices, vectors, and expressions. ">MatrixBase</a>. This leads to the following code:</p> <table class="example"> <tr> <th>Example:</th><th>Output: </th></tr> <tr> <td><div class="fragment"><div class="line"><span class="preprocessor">#include <Eigen/Dense></span></div> <div class="line"><span class="preprocessor">#include <iostream></span></div> <div class="line"></div> <div class="line"><span class="keyword">using namespace </span>Eigen;</div> <div class="line"></div> <div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> Derived1, <span class="keyword">typename</span> Derived2></div> <div class="line"><span class="keywordtype">void</span> copyUpperTriangularPart(<a class="code" href="classEigen_1_1MatrixBase.html">MatrixBase<Derived1></a>& dst, <span class="keyword">const</span> <a class="code" href="classEigen_1_1MatrixBase.html">MatrixBase<Derived2></a>& src)</div> <div class="line">{</div> <div class="line"> <span class="comment">/* Note the 'template' keywords in the following line! */</span></div> <div class="line"> dst.template triangularView<Upper>() = src.template triangularView<Upper>();</div> <div class="line">}</div> <div class="line"></div> <div class="line"><span class="keywordtype">int</span> main()</div> <div class="line">{</div> <div class="line"> <a class="code" href="classEigen_1_1Matrix.html">MatrixXi</a> m1 = <a class="code" href="classEigen_1_1DenseBase.html#a2278addf9a3c977d40322571a0df8ac9">MatrixXi::Ones</a>(5,5);</div> <div class="line"> <a class="code" href="classEigen_1_1Matrix.html">MatrixXi</a> m2 = <a class="code" href="classEigen_1_1DenseBase.html#a8e759dafdd9ecc446d397b7f5435f60a">MatrixXi::Random</a>(4,4);</div> <div class="line"> std::cout << <span class="stringliteral">"m2 before copy:"</span> << std::endl;</div> <div class="line"> std::cout << m2 << std::endl << std::endl;</div> <div class="line"> copyUpperTriangularPart(m2, m1.<a class="code" href="classEigen_1_1DenseBase.html#a6f5fc5fe9d3fb70e62d4a9b1795704a8">topLeftCorner</a>(4,4));</div> <div class="line"> std::cout << <span class="stringliteral">"m2 after copy:"</span> << std::endl;</div> <div class="line"> std::cout << m2 << std::endl << std::endl;</div> <div class="line">}</div> </div><!-- fragment --> </td><td><pre class="fragment">m2 before copy: 7 9 -5 -3 -2 -6 1 0 6 -3 0 9 6 6 3 9 m2 after copy: 1 1 1 1 -2 1 1 1 6 -3 1 1 6 6 3 1 </pre> </td></tr> </table> <p>The one line in the body of the function <code>copyUpperTriangularPart()</code> shows the second, more obscure use of the <code>template</code> keyword in C++. Even though it may look strange, the <code>template</code> keywords are necessary according to the standard. Without it, the compiler may reject the code with an error message like "no match for operator<".</p> <h1><a class="anchor" id="TopicTemplateKeywordExplanation"></a> Explanation</h1> <p>The reason that the <code>template</code> keyword is necessary in the last example has to do with the rules for how templates are supposed to be compiled in C++. The compiler has to check the code for correct syntax at the point where the template is defined, without knowing the actual value of the template arguments (<code>Derived1</code> and <code>Derived2</code> in the example). That means that the compiler cannot know that <code>dst.triangularPart</code> is a member template and that the following < symbol is part of the delimiter for the template parameter. Another possibility would be that <code>dst.triangularPart</code> is a member variable with the < symbol refering to the <code>operator<()</code> function. In fact, the compiler should choose the second possibility, according to the standard. If <code>dst.triangularPart</code> is a member template (as in our case), the programmer should specify this explicitly with the <code>template</code> keyword and write <code>dst.template triangularPart</code>.</p> <p>The precise rules are rather complicated, but ignoring some subtleties we can summarize them as follows:</p> <ul> <li>A <em>dependent name</em> is name that depends (directly or indirectly) on a template parameter. In the example, <code>dst</code> is a dependent name because it is of type <code><a class="el" href="classEigen_1_1MatrixBase.html" title="Base class for all dense matrices, vectors, and expressions. ">MatrixBase</a><Derived1></code> which depends on the template parameter <code>Derived1</code>.</li> <li>If the code contains either one of the contructions <code>xxx.yyy</code> or <code>xxx->yyy</code> and <code>xxx</code> is a dependent name and <code>yyy</code> refers to a member template, then the <code>template</code> keyword must be used before <code>yyy</code>, leading to <code>xxx.template yyy</code> or <code>xxx->template yyy</code>.</li> <li>If the code contains the contruction <code>xxx::yyy</code> and <code>xxx</code> is a dependent name and <code>yyy</code> refers to a member typedef, then the <code>typename</code> keyword must be used before the whole construction, leading to <code>typename xxx::yyy</code>.</li> </ul> <p>As an example where the <code>typename</code> keyword is required, consider the following code in <a class="el" href="group__TutorialSparse.html">Sparse matrix manipulations</a> for iterating over the non-zero entries of a sparse matrix type:</p> <div class="fragment"><div class="line">SparseMatrixType mat(rows,cols);</div> <div class="line"><span class="keywordflow">for</span> (<span class="keywordtype">int</span> k=0; k<mat.outerSize(); ++k)</div> <div class="line"> <span class="keywordflow">for</span> (SparseMatrixType::InnerIterator it(mat,k); it; ++it)</div> <div class="line"> {</div> <div class="line"> <span class="comment">/* ... */</span></div> <div class="line"> }</div> </div><!-- fragment --><p>If <code>SparseMatrixType</code> depends on a template parameter, then the <code>typename</code> keyword is required:</p> <div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div> <div class="line"><span class="keywordtype">void</span> iterateOverSparseMatrix(<span class="keyword">const</span> SparseMatrix<T>& mat;</div> <div class="line">{</div> <div class="line"> <span class="keywordflow">for</span> (<span class="keywordtype">int</span> k=0; k<m1.<a class="code" href="classEigen_1_1DenseBase.html#af080d3d3f82e0d4391f19af22a5eedb8">outerSize</a>(); ++k)</div> <div class="line"> <span class="keywordflow">for</span> (<span class="keyword">typename</span> SparseMatrix<T>::InnerIterator it(mat,k); it; ++it)</div> <div class="line"> {</div> <div class="line"> <span class="comment">/* ... */</span></div> <div class="line"> }</div> <div class="line">}</div> </div><!-- fragment --><h1><a class="anchor" id="TopicTemplateKeywordResources"></a> Resources for further reading</h1> <p>For more information and a fuller explanation of this topic, the reader may consult the following sources:</p> <ul> <li>The book "C++ Template Metaprogramming" by David Abrahams and Aleksey Gurtovoy contains a very good explanation in Appendix B ("The typename and template Keywords") which formed the basis for this page.</li> <li><a href="http://pages.cs.wisc.edu/~driscoll/typename.html">http://pages.cs.wisc.edu/~driscoll/typename.html</a></li> <li><a href="http://www.parashift.com/c++-faq-lite/templates.html#faq-35.18">http://www.parashift.com/c++-faq-lite/templates.html#faq-35.18</a></li> <li><a href="http://www.comeaucomputing.com/techtalk/templates/#templateprefix">http://www.comeaucomputing.com/techtalk/templates/#templateprefix</a></li> <li><a href="http://www.comeaucomputing.com/techtalk/templates/#typename">http://www.comeaucomputing.com/techtalk/templates/#typename</a> </li> </ul> </div></div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated on Mon Oct 28 2013 11:04:27 for Eigen by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.5 </li> </ul> </div> <!-- Piwik --> <!-- <script type="text/javascript"> var pkBaseURL = (("https:" == document.location.protocol) ? "https://stats.sylphide-consulting.com/piwik/" : "http://stats.sylphide-consulting.com/piwik/"); document.write(unescape("%3Cscript src='" + pkBaseURL + "piwik.js' type='text/javascript'%3E%3C/script%3E")); </script><script type="text/javascript"> try { var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", 20); piwikTracker.trackPageView(); piwikTracker.enableLinkTracking(); } catch( err ) {} </script><noscript><p><img src="http://stats.sylphide-consulting.com/piwik/piwik.php?idsite=20" style="border:0" alt="" /></p></noscript> --> <!-- End Piwik Tracking Code --> </body> </html>