<p>I discovered <a href="http://en.wikipedia.org/wiki/Template_metaprogramming" rel="noreferrer">template metaprogramming</a> more than 5 years ago and got a huge kick out of reading <a href="https://rads.stackoverflow.com/amzn/click/com/0201704315" rel="noreferrer" rel="nofollow noreferrer">Modern C++ Design</a> but I never found an opertunity to use it in real life.</p>

<p>Have <em>you</em> ever used this technique in real code?</p>

<blockquote>
  <p>Contributors to <a href="http://www.boost.org/" rel="noreferrer">Boost</a> need not apply ;o)</p>
</blockquote>

[{'answer_id': 63538, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': "<p>I've used it in the inner loops of a game's graphics code, where you want some level of abstraction and modularity but can't pay the cost of branches or virtual calls. Overall it was a better solution than a proliferation of handwritten special-case functions.</p>\n"}, {'answer_id': 63551, 'author': 'Eric', 'author_id': 4540, 'author_profile': 'https://Stackoverflow.com/users/4540', 'pm_score': 6, 'selected': True, 'text': '<p>I once used template metaprogramming in C++ to implement a technique called "symbolic perturbation" for dealing with degenerate input in geometric algorithms.  By representing arithmetic expressions as nested templates (i.e. basically by writing out the parse trees by hand) I was able to hand off all the expression analysis to the template processor.  </p>\n\n<p>Doing this kind of thing with templates is more efficient than, say, writing expression trees using objects and doing the analysis at runtime.  It\'s faster because the modified (perturbed) expression tree is then available to the optimizer at the same level as the rest of your code, so you get the full benefits of optimization, both within your expressions but also (where possible) between your expressions and the surrounding code.</p>\n\n<p>Of course you could accomplish the same thing by implementing a small DSL (domain specific language) for your expressions and the pasting the translated C++ code into your regular program.  That would get you all the same optimization benefits and also be more legible -- but the tradeoff is that you have to maintain a parser.</p>\n'}, {'answer_id': 63594, 'author': 'Leon Timmermans', 'author_id': 4727, 'author_profile': 'https://Stackoverflow.com/users/4727', 'pm_score': 1, 'selected': False, 'text': '<p>Yes I have, mostly to do some things that resemble duck-typing when I was wrapping a legacy API in a more modern C++ interface.</p>\n'}, {'answer_id': 63759, 'author': 'maccullt', 'author_id': 4945, 'author_profile': 'https://Stackoverflow.com/users/4945', 'pm_score': 1, 'selected': False, 'text': "<p>No I haven't used it in production code.</p>\n\n<p>Why?</p>\n\n<ol>\n<li>We have to support 6+ platforms with <em>native</em> <em>platform</em> compilers. It's\nhard enough to use STL in this environment let alone modern template\ntechniques.</li>\n<li>Developers don't seem to be keeping up C++ advances anymore. We use C++\nwhen we have to. We have legacy code with legacy designs. New code is \ndone in something else e.g., Java, Javascript, Flash.</li>\n</ol>\n"}, {'answer_id': 65114, 'author': 'Calliphony', 'author_id': 9050, 'author_profile': 'https://Stackoverflow.com/users/9050', 'pm_score': -1, 'selected': False, 'text': "<p>Many programmers don't use templates much because of the poor compiler support up until recently. However, while templates have had a lot of issues in the pas, newer compilers have much better support.  I write code that has to work with GCC on Mac and Linux as well as Microsoft Visual C++ and it's only with GCC 4 and VC++ 2005 that these compiler have supported the standard really well. </p>\n\n<p>Generic programming via templates is not something you need all the time but is definitely a useful code to have in your toolbox.</p>\n\n<p>The obvious example container classes but templates are also useful for many other things. Two examples from my own work are:</p>\n\n<ul>\n<li>Smart pointers ( e.g. Reference-counted, copy-on-write, etc.)</li>\n<li>Math support classes such as Matrices, vectors, splines, etc. that need to support a variety of data types and still be efficient.</li>\n</ul>\n"}, {'answer_id': 69397, 'author': 'Jared A Hicks', 'author_id': 5088, 'author_profile': 'https://Stackoverflow.com/users/5088', 'pm_score': 4, 'selected': False, 'text': '<p>Template metaprogramming and expression templates are becoming more popular in the scientific community as optimization methods that offload some of the computational effort onto the compiler while maintaining some abstraction.  The resulting code is larger and less readable, but I have used these techniques to speed up linear algebra libraries and quadrature methods in FEM libraries.</p>\n\n<p>For application-specific reading, <a href="http://ubiety.uwaterloo.ca/~tveldhui/" rel="noreferrer">Todd Veldhuizen</a> is a big name in this area.  A popular book is <a href="http://www.math.wayne.edu/~yang/book.htm" rel="noreferrer">C++ and Object Oriented Numeric Computing for Scientists and Engineers</a> by Daoqi Yang.</p>\n'}, {'answer_id': 74856, 'author': 'user12310', 'author_id': 12310, 'author_profile': 'https://Stackoverflow.com/users/12310', 'pm_score': 3, 'selected': False, 'text': "<p>Most programmers who use template metaprogramming use it indirectly, through libraries like boost. They don't even probably know what is happening behind the scenes, only that it makes the syntax of certain operations much much easier.</p>\n"}, {'answer_id': 75023, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': -1, 'selected': False, 'text': "<p>Don't do that. The reason behind that is as follows: by nature of template metaprogramming, if some part of your logic is done at compile-time, every logic that it is dependent on must be done at compile time as well. Once you start it, do one portion of your logic at compile time, there is no return. The snowball will keep on rolling and there is no way to stop it.</p>\n\n<p>For example, you can't iterate on the elements of a boost::tuple&lt;>, because you can only access them at compile time. You must use template metaprogramming to achieve what would have been easy and straightforward C++, and this <em>always</em> happens when the users of C++ aren't careful enough not to move too many things to compile-time. Sometimes it is difficult to see when a certain use of compiletime logic would become problematic, and sometimes programmers are eager to try and test what they've read in Alexandrescu's. In any case, this is a very bad idea in my opinion.</p>\n"}, {'answer_id': 193458, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>I use template metaprogramming all the time, but in D, not C++.  C++\'s template metalanguage was originally designed for simple type parametrization and became a Turing complete metalanguage almost by accident.  It is therefore a Turing tarpit that only Andrei Alexandrescu, not mere mortals, can use.</p>\n\n<p>D\'s template sublanguage, on the other hand, was actually designed for metaprogramming beyond simple type parameterization.  Andrei Alexandrescu <a href="http://digitalmars.com/d/2.0/phobos/std_algorithm.html" rel="nofollow noreferrer">seems to love it,</a> but other people can actually understand his D templates.  It\'s also powerful enough that someone wrote a <a href="http://h3.team0xf.com/ctrace/" rel="nofollow noreferrer">compile-time raytracer</a> in it as a proof of concept.</p>\n\n<p>I guess the most useful/non-trivial metaprogram I ever wrote in D was a function template that, given a struct type as the template parameter and a list of column header names in an order corresponding to the variable declarations in the struct as a runtime parameter, will read in a CSV file, and return an array of structs, one for each row, with each struct field corresponding to a column.  All type conversions (string to float, int, etc.) are done automatically, based on the types of the template fields.</p>\n\n<p>Another good one, which mostly works, but still doesn\'t handle a few cases properly, is a deep copy function template that handles structs, classes, and arrays properly.  It uses only compile time reflection/introspection, so that it can work with structs, which, unlike full-blown classes, have no runtime reflection/introspection capabilities in D because they\'re supposed to be lightweight.</p>\n'}, {'answer_id': 772727, 'author': 'Nathan Monteleone', 'author_id': 27130, 'author_profile': 'https://Stackoverflow.com/users/27130', 'pm_score': 5, 'selected': False, 'text': '<p>I\'ve found policies, described in Modern C++ Design, really useful in two situations:</p>\n\n<ol>\n<li><p>When I\'m developing a component that I expect will be reused, but in a slightly different way. Alexandrescu\'s suggestion of using a policy to reflect a design fits in really well here - it helps me get past questions like, "I could do this with a background thread, but what if someone later on wants to do it in time slices?" Ok fine, I just write my class to accept a ConcurrencyPolicy and implement the one I need at the moment. Then at least I know the person who comes behind me can write and plug in a new policy when they need it, without having to totally rework my design.  Caveat: I have to reign myself in sometimes or this can get out of control -- remember the <a href="http://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it" rel="noreferrer" title="YAGNI">YAGNI</a> principle!</p></li>\n<li><p>When I\'m trying to refactor several similar blocks of code into one. Usually the code will be copy-pasted and modified slightly because it would have had too much if/else logic otherwise, or because the types involved were too different. I\'ve found that policies often allow for a clean one-fits-all version where traditional logic or multiple inheritance would not.</p></li>\n</ol>\n'}, {'answer_id': 854167, 'author': 'Motti', 'author_id': 3848, 'author_profile': 'https://Stackoverflow.com/users/3848', 'pm_score': 2, 'selected': False, 'text': '<p>Almost 8 months after asking this I\'ve finally used some TMP, I use a <a href="http://www.ddj.com/cpp/184403813" rel="nofollow noreferrer">TypeList</a> of interfaces in order to implement QueryInterface in a base class.</p>\n'}, {'answer_id': 1010048, 'author': 'KitsuneYMG', 'author_id': 86515, 'author_profile': 'https://Stackoverflow.com/users/86515', 'pm_score': 2, 'selected': False, 'text': '<p>I use it with boost::statechart for large statemachines.</p>\n'}, {'answer_id': 3051221, 'author': 'Carl', 'author_id': 13760, 'author_profile': 'https://Stackoverflow.com/users/13760', 'pm_score': 2, 'selected': False, 'text': "<p>I've used it quite a bit with DSP code, especially FFTs, fixed size circular buffers, hadamard transforms and the like. </p>\n"}, {'answer_id': 3586490, 'author': 'deft_code', 'author_id': 28817, 'author_profile': 'https://Stackoverflow.com/users/28817', 'pm_score': 3, 'selected': False, 'text': "<p>Template meta programming is a wonderful and power technique when writing c++ <strong><em>libraries</em></strong>.  I've used it a few time in custom solutions, but usually a less elegant old style c++ solution is easier to get through code review and easier to maintain for other users.</p>\n\n<p>However, I've got a lot of mileage out of template meta programming when writing reusable components/libraries.  I'm not talking anything as large some of Boost's stuff just smallish components that will be reused frequently.</p>\n\n<p>I used TMP for a singleton system where the user could specify what type of singleton they desired.  The interface was very basic.  Underneath it was powered by heavy TMP.</p>\n\n<pre><code>template&lt; typename T &gt;\nT&amp; singleton();\n\ntemplate&lt; typename T &gt;\nT&amp; zombie_singleton();\n\ntemplate&lt; typename T &gt;\nT&amp; phoenix_singleton();\n</code></pre>\n\n<p>Another successful use was simplifying our IPC layer.  It is built  using classic OO style. Each message needs to derive from an abstract base class and override some serialization methods.  Nothing too extreme, but it generates a lot of boiler plate code.</p>\n\n<p>We threw some TMP at it and automated the generation of all the code for the simple case of messages containing only POD data.  The TMP messages still used the OO backend but they massively reduce the amount of boiler plate code.  The TMP was also used to generate the message vistor.  Over time all our message migrated to the TMP method.  It was easier and less code to build a simple POD struct just for message passing and add the few (maybe 3) lines needed to get the TMP to generate the classes than it was to derive a new message to send a regular class across the IPC framework.</p>\n"}, {'answer_id': 4312165, 'author': 'AntonLosev', 'author_id': 524849, 'author_profile': 'https://Stackoverflow.com/users/524849', 'pm_score': 2, 'selected': False, 'text': '<p>For those familiar with Oracle Template Library (<a href="http://otl.sourceforge.net/" rel="nofollow noreferrer">OTL</a>), boost::any and <a href="http://loki-lib.sourceforge.net/" rel="nofollow noreferrer">Loki</a> library (the one described in Modern C++ Design) here\'s the proof of concept TMP code that enables you to store one row of otl_stream in <code>vector&lt;boost::any&gt;</code> container and access data by column number. And \'Yes\', I\'m going to incorporate it in production code.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;string&gt;\n#include &lt;Loki/Typelist.h&gt;\n#include &lt;Loki/TypeTraits.h&gt;\n#include &lt;Loki/TypeManip.h&gt;\n#include &lt;boost/any.hpp&gt;\n#define OTL_ORA10G_R2\n#define OTL_ORA_UTF8\n#include &lt;otlv4.h&gt;\n\nusing namespace Loki;\n\n/* Auxiliary structs */\ntemplate &lt;int T1, int T2&gt;\nstruct IsIntTemplateEqualsTo{\n    static const int value = ( T1 == T2 );\n};\n\ntemplate &lt;int T1&gt;\nstruct ZeroIntTemplateWorkaround{\n    static const int value = ( 0 == T1? 1 : T1 );\n};\n\n\n/* Wrapper class for data row */\ntemplate &lt;class TList&gt;\nclass T_DataRow;\n\n\ntemplate &lt;&gt;\nclass T_DataRow&lt;NullType&gt;{\nprotected:\n    std::vector&lt;boost::any&gt; _data;\npublic:\n    void Populate( otl_stream&amp; ){};\n};\n\n\n/* Note the inheritance trick that enables to traverse Typelist */\ntemplate &lt;class T, class U&gt;\nclass T_DataRow&lt; Typelist&lt;T, U&gt; &gt;:public T_DataRow&lt;U&gt;{\npublic:\n    void Populate( otl_stream&amp; aInputStream ){\n        T value;\n        aInputStream &gt;&gt; value;\n        boost::any anyValue = value;\n        _data.push_back( anyValue );\n\n        T_DataRow&lt;U&gt;::Populate( aInputStream );\n    }\n\n    template &lt;int TIdx&gt;\n    /* return type */\n    Select&lt;\n        IsIntTemplateEqualsTo&lt;TIdx, 0&gt;::value,\n        typename T,\n        typename TL::TypeAt&lt;\n            U,\n            ZeroIntTemplateWorkaround&lt;TIdx&gt;::value - 1\n        &gt;::Result\n    &gt;::Result\n    /* sig */\n    GetValue(){\n    /* body */\n        return boost::any_cast&lt;\n            Select&lt;\n                IsIntTemplateEqualsTo&lt;TIdx, 0&gt;::value,\n                typename T,\n                typename TL::TypeAt&lt;\n                    U,\n                    ZeroIntTemplateWorkaround&lt;TIdx&gt;::value - 1\n                &gt;::Result\n            &gt;::Result\n        &gt;( _data[ TIdx ] );\n    }\n};\n\n\nint main(int argc, char* argv[])\n{\n    db.rlogon( "AMONRAWMS/WMS@amohpadb.world" ); // connect to Oracle\n    std::cout&lt;&lt;"Connected to oracle DB"&lt;&lt;std::endl;\n    otl_stream o( 1, "select * from blockstatuslist", db );\n\n    T_DataRow&lt; TYPELIST_3( int, int, std::string )&gt; c;\n    c.Populate( o );\n    typedef enum{ rcnum, id, name } e_fields; \n    /* After declaring enum you can actually acess columns by name */\n    std::cout &lt;&lt; c.GetValue&lt;rcnum&gt;() &lt;&lt; std::endl;\n    std::cout &lt;&lt; c.GetValue&lt;id&gt;() &lt;&lt; std::endl;\n    std::cout &lt;&lt; c.GetValue&lt;name&gt;() &lt;&lt; std::endl;\n    return 0;\n};\n</code></pre>\n\n<p>For those not familiar with mentioned libraries. </p>\n\n<p>The problem with OTL\'s otl_stream container is that one can access columns data only in sequential order by declaring variables of appropriate type and applying the <code>operator &gt;&gt;</code> to otl_stream object in the following way:</p>\n\n<pre><code>otl_stream o( 1, "select * from blockstatuslist", db );\nint rcnum; \nint id;\nstd::string name;\no &gt;&gt; rcnum &gt;&gt; id &gt;&gt; name; \n</code></pre>\n\n<p>It\'s not always convenient. The workaround is to write some wrapper class and to populate it with data from otl_stream. The desire is to be able to declare the list of column types and then: </p>\n\n<ul>\n<li>take the type T of the column</li>\n<li>declare variable of that type</li>\n<li>apply <code>olt_stream::operator &gt;&gt;(T&amp;)</code> </li>\n<li>store the result (in the vector of boost::any)</li>\n<li>take the type of the next column and repeat until all columns are processed</li>\n</ul>\n\n<p>You can do all this with the help of Loki\'s <code>Typelist</code> struct, template specialization and inheritance.</p>\n\n<p>With the help of Loki\'s library constructs you can also generate bunch of GetValue functions that return values of appropriate type deducing it from column\'s number (actually number of type in <code>Typelist</code>).</p>\n'}]
['https://Stackoverflow.com/questions/63494', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3848/']