C++ Template Metaprogramming

David Abrahams, Aleksey Gurtovoy

Mentioned 18

At long last, this much-awaited book delivers practical metaprogramming into the hands of the everyday C++ programmer.

More on Amazon.com

Mentioned in questions and answers.

This question attempts to collect the few pearls among the dozens of bad C++ books that are published every year.

Unlike many other programming languages, which are often picked up on the go from tutorials found on the Internet, few are able to quickly pick up C++ without studying a well-written C++ book. It is way too big and complex for doing this. In fact, it is so big and complex, that there are very many very bad C++ books out there. And we are not talking about bad style, but things like sporting glaringly obvious factual errors and promoting abysmally bad programming styles.

Please edit the accepted answer to provide quality books and an approximate skill level — preferably after discussing your addition in the C++ chat room. (The regulars might mercilessly undo your work if they disagree with a recommendation.) Add a short blurb/description about each book that you have personally read/benefited from. Feel free to debate quality, headings, etc. Books that meet the criteria will be added to the list. Books that have reviews by the Association of C and C++ Users (ACCU) have links to the review.

Note: FAQs and other resources can be found in the C++ tag info and under . There is also a similar post for C: The Definitive C Book Guide and List


Introductory, no previous programming experience

  • Programming: Principles and Practice Using C++ (Bjarne Stroustrup) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.

Introductory, with previous programming experience

  • C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]

  • A Tour of C++ (Bjarne Stroustrup) (EBOOK) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.

  • Accelerated C++ (Andrew Koenig and Barbara Moo) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction into the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach at teaching the language.) [Review]

  • Thinking in C++ (Bruce Eckel) Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they’re marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const), with no official errata list. A partial 3rd party errata list is available at (http://www.computersciencelab.com/Eckel.htm), but it’s apparently not maintained.

* Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.

Best practices

  • Effective C++ (Scott Meyers) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]

  • Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.

  • Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]


  • More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.

  • Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]

  • More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object oriented programming in C++ and correct use of the STL. [Review]

  • Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using nonmember functions and the single responsibility principle. [Review]

  • C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]

  • C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition is scheduled for 2017. [Review]


  • Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multimethods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]

  • C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)

  • C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications.

  • Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by typetraits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.

Reference Style - All Levels

  • The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much alike it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review]

  • C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]

  • The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]

C++11/14 References:

  • The C++ Standard (INCITS/ISO/IEC 14882-2011) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. As usual, the first release was quite expensive ($300+ US), but it has now been released in electronic form for $60US.

  • The C++14 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++17.

  • Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++1y/C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.

  • The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.

  • The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.

  • cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.

Classics / Older

Note: Some information contained within these books may not be up-to-date or no longer considered best practice.

  • The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.

  • Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]

  • Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.

  • Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly a good read, if it only was up to date. It was written long before C++98, and misses on many features (e.g. namespaces) important for large scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is expected in 2015.

  • Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.

  • The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however this is book goes through the entire C++ standard of the time explaining the rationale, the possible implementations and features of the language. This is not a book not learn programming principles and patterns on C++, but to understand every aspect of the C++ language.

I am learning templates. Which book is worth buying for doing template programming?

I already have The C++ Programming Language and Effective C++.

"C++ Templates: The Complete Guide (Vandevoorde & Josuttis)" is excellent for the theory. Then you can learn even more about actual templating practice by looking at how templates are used in the Boost library.

Those two books are pretty good in my opinion and they helped me a lot


The first one explains how templates work. The second book is more about how to use them. I recommend you to read the first book before starting with Modern C++ Design because that's heavy stuff.

Maybe a bit mind-boggling if you are just learning, but after the books you mention, you may want to read Andrei Alexandrescu's Modern C++ Design, if only to learn what can be accomplished through templates. Besides, it discusses many advanced aspects of templates wonderfully.

C++ Templates: The Complete Guide is your best bet. You could also learn about the Standard Library which heavily uses templates.

Effective STL by Scott Meyers

There is a hidden treasure in C++ templates that very few people are aware of: C++ Common Knowledge: Essential Intermediate Programming.

The last 15 chapters of that book both teaches better and complements C++ Template Metaprogramming in some respects. I strongly recommend anyone who is to learn templates to read this book foremost.

Both Modern C++ design and C++ Template Metaprogramming are very good (and quite advanced) books on the subject. I have a strong personal preference for the first.

Possible Duplicate(s):

Where can I learn about the C++ Standard Template Library (STL)?

The Definitive C++ Book Guide and List

I am having very less knowledge on templates and STL. So looking for a good for STL.

If you want a good book for learning templates in general, I would recommend:

C++ Templates: The Complete Guide

If you then become a complete addict, you can move on to:

C++ Template Metaprogramming

(and perhaps look into counseling for your mental issues.. :-))

If you just want a book on STL, there are many, but the best I've found is:

The C++ Standard Library: A Tutorial and Reference

I'm working on a C++ project with extensive compile-time computations. Long compilation time is slowing us down. How might I find out the slowest parts of our template meta-programs so I can optimize them? (When we have slow runtime computations, I have many profilers to choose from, e.g. valgrind's callgrind tool. So I tried building a debug GCC and profiling it compiling our code, but I didn't learn much from that.)

I use GCC and Clang, but any suggestions are welcome.

I found profile_templates on Boost's site, but it seems to be thinly documented and require the jam/bjam build system. If you show how to use it on a non-jam project1, I will upvote you. https://svn.boost.org/svn/boost/sandbox/tools/profile_templates/ appears to count number-of-instantiations, whereas counting time taken would be ideal.

1 Our project uses CMake and is small enough that hacking together a Jamfile just for template profiling could be acceptable.

The classic book C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond comes with a 20 page appendix on profiling compile-time costs. It has a companion CD with the code that generates the graphs in that appendix.

Another paper is http://aszt.inf.elte.hu/~gsd/s/cikkek/profiling/profile.pdf, perhaps that is of use to you.

Yet another, but more labor-intensive, way is to count the number of instantiations of each class from your compiler output.

I've been talking with friends and some completely agree that templates in C++ should be used, others disagree entirely.

Some of the good things are:

  • They are more safe to use (type safety).
  • They are a good way of doing generalizations for APIs.

What other good things can you tell me about C++ templates?

What bad things can you tell me about C++ templates?

Edit: One of the reasons I'm asking this is that I am studying for an exam and at the moment I am covering the topic of C++ templates. So I am trying to understand a bit more on them.

Templates are a very powerful mechanism which can simplify many things. However to use them properly requires much time and experience - in order to decide when their usage is appropriate.

For me the most important advantages are:

  • reducing the repetition of code (generic containers, algorithms)
  • reducing the repetition of code advanced (MPL and Fusion)
  • static polymorphism (=performance) and other compile time calculations
  • policy based design (flexibility, reusability, easier changes, etc)
  • increasing safety at no cost (i.e. dimension analysis via Boost Units, static assertions, concept checks)
  • functional programming (Phoenix), lazy evaluation, expression templates (we can create Domain-specific embedded languages in C++, we have great Proto library, we have Blitz++)
  • other less spectacular tools and tricks used in everyday life:
    • STL and the algorithms (what's the difference between for and for_each)
    • bind, lambda (or Phoenix) ( write clearer code, simplify things)
    • Boost Function (makes writing callbacks easier)
    • tuples (how to genericly hash a tuple? Use Fusion for example...)
    • TBB (parallel_for and other STL like algorithms and containers)
  • Can you imagine C++ without templates? Yes I can, in the early times you couldn't use them because of compiler limitations.
  • Would you write in C++ without templates? No, as I would lose many of the advantages mentioned above.


  • Compilation time (for example throw in Sprit, Phoenix, MPL and some Fusion and you can go for a coffee)
  • People who can use and understand templates are not that common (and these people are useful)
  • People who think that they can use and understand templates are quite common (and these people are dangerous, as they can make a hell out of your code. However most of them after some education/mentoring will join the group mentioned in the previous point)
  • template export support (lack of)
  • error messages could be less cryptic (after some learning you can find what you need, but still...)

I highly recommend the following books:

I'm a practicing C++ programmer (on Unix and gcc 3.x) for the past 6-7 years. I've read Scott Meyer's Effective C++, More Effective C++ and Effective STL cover-to-cover and have lived and practiced his suggestions/techniques along with Boost. I would like to move on to the more advanced aspects of C++ - something along the lines of 'Modern C++ Design' by Andrei Alexandrescu. However, before starting to read this, I am wondering if I should spend time reading Herb Sutter's Exceptional C++ books as well. How would you compare the Effective C++ series with Sutter's books?

Thanks a lot in advance for your response.

Frankly, Herb Sutter yanks a lot in the exception safety ever since the introduction of the idea in one of the journals of the pre-2000 age. The fact he used it a lot on replication and transactional systems makes sense, and unless you are a huge follower and interested in only the software of such 'safety' kind you will be bored to death. Meyers is far more practical and engaging.

Besides, if you want to move on, there are other books in the series, notably from the legends and not the writers for the sake of writing. Look up the bits from Nicolai Josuttis (C++ Templates: The Complete Guide), Aleksey Gurtovoy (C++ Template Metaprogramming) and more recently 'Daddy 2' Stepanov. In my opinion, they are more influential, knowledgable, practical and shaping than anything DDJ or exception safety induced writeups...

And of course, if you ever need to go back to basics (and there is always a reason to), one of the best possible books on the subject is by the daddy himself: The C++ Programming Language (most underestimated and skimmed over book out there).

what is the most advanced c or c++ book you ever read? i am asking this because i already read lots and lots of books on c and c++ on a lot of topics including (object oriented programming-data structures and algorithms-network programming-parallel programming (MPI-PThreads-OpenMP-Cilk-Cuda)-boost library....). So whats next. I still want to advance.. especially in c.

Hey nobody mentioned about Bruce Eckel's Thinking in C++ Volume 1 And Volume 2. When I read it as the first book it went straight way above my head. However as now I have good experience and have read books like Effective/Exceptional C++ so Eckel's book is now an ordinary stuff. However no doubt its a very popular book (4.5 stars on Amazon - 84 customer reviews).

Large Scale C++ Design by John Lakos.

Practical advice on managing the complexity of compiling/linking and executing large C++ programs. Talks a lot about decoupling and how to avoid the many kinds of dependencies that arise in C++.

(This is something most C#/Java developers, and sadly some C++-devs too, rarely understand. IMO, it's a pain they need to. I wish we had modules in C++ already.)

My favourite "difficult" C++ book is this Template Metaprogramming one: C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond.

You really want to test your mental limits? Then try these:

Alexandrescu: Modern C++ Design

Abrahams&Gurtovoy: C++ Template Metaprogramming

These books look deceiptively thin, but they stretch the limits of template programming, your C++ compiler, and your brain.

It seems to me there aren't half as many books about C programming as there are about C++. The language just isn't that complex.

One interesting read might be P. J. Plauger The Standard C Library. It is supposed to contain some masterful code. It's on my to-read list.

I am not sure if you would consider these advanced, but I would surely put them in the category of must have references:

The C++ Programming Language Special Edition (3rd) by Bjarne Stroustrup

The C++ Standard Library: A Tutorial and Reference by Nicolai M. Josuttis

The other books I would recommend have already been listed by others.

I haven't touch C++ in more then 8 years. I recently had to do fix some C++ code, and although I still can code, I feel like I no more belongs to the camp of C++ programmers. I don't know any libraries, didn't pay attention to the new language features / improvements / best practices.

Qt Creator and Qt seems like a nice toolset for what I need now, since I'm interested mostly in cross platform development.

What would be good resources for someone like me to quickly re-learn C++ and best practices in shortest period of time?

I have been doing mostly java and common lisp in the meantime, with a short strides to C, flex, Scala and Haskell.

Read :

Those are references books on C++ that resume all the modern effective pratices, philosophies and knowledge on C++ (without going into Meta-Programmation stuff).

Then if you want to go farther, read :

About libraries: first learn about the STL and learn to use Boost as a "standard" STL extension.

I read about meta-programming, and found it was really interesting. For example, check to see if the number is prime, calculate fibonacci number...I'm curious about its practical usage, if we can convert all runtime solution to meta-programming, the the application would perform much better. Let's say to find max value of an array. We would take O( n ) at run time if it was not sorted. Is it possible to get O( 1 ) with meta-programing?


You can't because metaprogramming only works for inputs that are known at compile time. So you can have a metafunction that calculates a Fibonacci number given a constant known at compile time:

int value = Fibonacci<5>::Value;

But it won't work for values that are inputted by a user at runtime:

int input = GetUserInput();
int value = Fibonacci<input>::Value; // Does not compile

Sure, you can recompile the program every time you get new values, but that becomes impractical for non-trivial programs.

Keep in mind that metaprogramming in C++ is basically a "useful accidental abuse" of the way C++ handles templates. Template metaprogramming was definitely not what the C++ standards committee had in mind when creating the C++ standards prior to C++0x. You can only push the compiler so much until you get internal compiler errors (that has changed nowadays with newer compilers, but you still shouldn't go overboard).

There's an (advanced-level) book dedicated to C++ template metaprogramming if you want to see what they are really useful for.

How to learn c++ generic programming and template? Recommend some good books about this topic.

C++ Templates: The Complete Guide by Nicolai M. Josuttis is a good book for templates.

I am a vc++ developer but I spend most of my time learning c++.What are all the things I should know as a vc developer.

I don't understand why people here post things about WinAPI, .NET, MFC and ATL.

You really must know the language. Another benefit would be the cross platform libraries. C++ is not about GUI or Win32 programming. You can write Multi-Platform application with libraries like boost, QT, wxWidgets (may be some XML parser libs).

Visual C++ is a great IDE to develop C++ application and Microsoft is trying hard to make Visual C++ more standard conform. Learning standard language without dialects (MS dialect as well) will give you an advantage of Rapid Development Environment combined with multi-platform portability. There are many abstraction libraries out there, which work equally on Windows, Linux, Unix or Mac OS. Debugger is a great app in VC++ but not the first thing to start with. Try to write unit tests for your application. They will ensure on next modifications that you did not broke other part of tested (or may be debugged:) code.

Do not try to learn MFC or ATL from scratch, try to understand STL. MFC is old, and new version are more or less wrapper around ATL. ATL is some strange lib, which tries to marry STL-idioms (and sometimes STL itself) and WinAPI. But using ATL concepts without knowing what is behind, will make you unproductive as well. Some ATL idioms are very questionable and might be replaced by some better from boost or libs alike.

The most important things to learn are the language philosophy and concepts. I suggest you to dive into the language and read some serious books:

When here you will be a very advanced C++ developer Next books will make guru out of you:

Remember one important rule: If you have a question, try to find an answer to it in ISO C++ Standard (i.e. Standard document) first. Doing so you will come along many other similar things, which will make you think about the language design.

Hope that book list helps you. Concepts from these books you will see in all well designed modern C++ frameworks.

With Kind Regards,

Does it make any sense to write code like this?

template<bool X>
double foo(double x){
     return (X) ? moo(x) : bar(x);

I know that there are better ways to implement this example, but I wonder, if it is safe in general to assume that the compiler will identify dead code and instantiates this as

double foo<true>(double x){return moo(x);}
double foo<false>(double x){return bar(x);}

The thing to keep in mind here is templates are different from language features like generics in languages like C#.

It is a fairly safe simplification to think of templates as an advanced preprocessor that is type aware. This is the idea behind Template metaprogramming (TMP) which is basically compile time programming.

Much like the preprocessor templates are expanded and the result goes through all of the same optimization stages as your normal logic.

Here is an example of rewritting your logic in a style more consistent with TMP. This uses function specialization.

template<bool X>
double foo(double x);

double foo<true>(double x)
    return moo(x);

double foo<false>(double x)
    return bar(x);

TMP was actually discovered as a happy accident and is pretty much the bread and butter of the STL and Boost.

It is turing complete so you can do all sorts of computation at compile time.

It is lazily evaluated so you could implement your own compile time asserts by putting invalid logic in a specialization of a template that you don't want to be used. For example if I were to comment out the foo<false> specialization and tried to use it like foo<false>(1.0); the compiler would complain, although it would be perfectly happy with foo<true>(1.0);.

Here is another Stack Overflow post that demonstrates this.

Further reading if interested:

  1. Modern C++ Design
  2. C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond
  3. Effective C++

I am working with the libMesh FEM library and am trying to develop a class (EqCore) that inherits from libMesh. This class will provide some additional features that are inherited again by a class that I want to actually use (MainEq).

The two functions, set_constant and get_constant, are causing the error below. These worked as shown with a different inheritance scheme (see Inheritance of template class with a template member function in C++). The difference with this problem is that now the template parameter (Type) is actually a class that gets inherited. Is this a dangerous practice?

I would appreciate any help getting this code working or finding an alternate method.


In member function ‘void EqCore::set_constant(std::string, ParamType)’: test_libmesh.cpp:26:57: error: expected primary-expression before ‘>’ token

In member function ‘ParamType EqCore::get_constant(std::string)’: /home/slaughter/Documents/programs/source/test_libmesh.cpp:31:76: error: expected primary-expression before ‘>’ token


//! \example test_libmesh.cpp

#include <string>
using std::string;

// libMesh includes
#include <libmesh.h>
#include <libmesh_common.h> 
#include <equation_systems.h>
#include <transient_system.h>
#include <explicit_system.h>
#include <parameters.h>
#include <mesh.h>
using namespace libMesh;

// Fundamental behavior that will be used among many classes
template <typename Type> class EqCore : Type{

        // Class constructor
        EqCore(EquationSystems& sys, string name) : Type(sys, name, 1){}

        // A function for storing a constant value (causes error)
        template<typename ParamType> void set_constant(std::string name, ParamType var){  
            Type::get_equation_systems().parameters.set<ParamType>(name) = var;

        // A function for retrieving a constant value (causes error)
        template<typename ParamType> ParamType get_constant(std::string name){  
            ParamType output = Type::get_equation_systems().parameters.get<ParamType>(name);
            return output;

// A test class derived
class MainEq : public EqCore<ExplicitSystem>{

        // Constructor
        MainEq(EquationSystems& sys) : EqCore(sys, "main"){ }   


// Begin main function
int main (int argc, char** argv){

    // Initialize libMesh and create an empty mesh
    LibMeshInit init (argc, argv);
    Mesh mesh;

    // Test w/o any of the above classes
    EquationSystems eq_sys(mesh);
    eq_sys.parameters.set<double>("test1") = 1;
    printf("Test 1: %f\n", eq_sys.parameters.get<double>("test1"));

    // Test my class set/get functions
    MainEq eq(eq_sys);
    eq.set_constant<double>("test2", 2);
    printf("Test 2: %f\n", eq.get_constant<double>("test2"));   

In C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond, by David Abrahams, Aleksey Gurtovoy (Amazon) it is explained as follows:

double const pi = 3.14159265359;

template <class T>
int f(T& x)
    return x.convert<3>(pi);

T::convert might be a member function template, in which case the highlighted code passes pi to a specialization of convert<3>. It could also turn out to be a data member, in which case f returns (x.convert < 3 ) > pi. That isn't a very useful calculation, but the compiler doesn't know it.

The template keyword tells the compiler that a dependent name is a member template:

template <class T>
int f(T& x)
    return x.template convert<3>(pi);

If we omit template, the compiler assumes that x.convert does not name a template, and the < that follows it is parsed as the less-than operator.

I tried boost::mpl recently and it seems both awesome and horrible. Sometimes the compilation error information is rather confusing.

This time I get problem on the following code:

#include <iostream>
#include <boost/type_traits/is_same.hpp>
#include <boost/mpl/integral_c_tag.hpp>
#include <boost/mpl/tag.hpp>
#include <typeinfo>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/range_c.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/copy.hpp>

//Using metafunction tag<> to acquire type so that mpl will only output integers.

struct mpl_func2
    template<typename T>
    void operator()(T t)
        if(boost::is_same<boost::mpl::tag<T>::type, boost::mpl::integral_c_tag>::value)

Here is the error messages:

error: type/value mismatch at argument 1 in template parameter list for 'template struct boost::is_same'

error: expected a type, got 'boost::mpl::tag::type'

Unfortunately, you are mixing the concepts of compile-time and runtime programming.

In the Template Metaprogramming world, you would use something like enable_if (http://en.cppreference.com/w/cpp/types/enable_if) to accomplish what you want.

In that page there are numerous examples that will illustrate how you can select which implementation to execute at runtime, based on your compile-time types.

I would also suggest reading Dave Abraham's book on MPL (http://www.amazon.com/Template-Metaprogramming-Concepts-Techniques-Beyond/dp/0321227255).

Once you understand MPL, you will be able to develop highly optimized programs.

I work on an open source project focused around Biblical texts. I would like to create a standard string format to build up a search string. I would then need to parse the search string and run the search with the options given. There are a number of different options, from scope of the search, to searching multiple texts, to wildcards, etc.

I'm thinking that using something like lex/yacc to generate a parser for this format might be a good idea. I think the Xapian project uses lemony to achieve a similar goal. My question is, is using one (or more) of these tools the best way to accomplish this?

In addition to the question, I would appreciate any links to resources on these tools (and any others that might be options). The biggest problem I've run into so far is that most of the examples and tutorials are either geared towards a programming language or something simple like a calculator rather than parsing a string format.

If you're trying to build a parser in C++ have a look at


It certainly is advanced C++, but it will build quite complex and performant parsers from C++ templates without code generation. It took me a few days to get into it, but using and modifying the samples that was straight forward. I also recommend reading the following book:

C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond by David Abrahams and Aleksey Gurtovoy

The templates tag is used in multiple contexts:

C++ templates

Templates in C++ allow for generic programming and meta-programming. The C++ Book Guide contains books treating templates as well, especially:

Before asking a question, consider looking into these FAQs first:

There are also useful questions on StackOverflow:


Other templates (PHP, django, drupal, mediawiki, etc.)

There are several varieties of template engines used with web servers, web applications, and web scripting languages. Questions for these types of templates should use the language specific tag.

The web server or scripting language templates are different from templates as used in C++ or generics as used in Java. These templates are used to help with separating view or presentation of data with the business logic generating or transforming the data.

PHP template questions should use the specific template product tag such as , , etc.

django template questions should use .

drupal template questions should use .

mediawiki template questions should use .

I'm trying to understand C++ code with a C basis. I don't have enough time so there wasn't time to study C++ syntax properly and then dive in. But I'm able to read through the lines but there is one thing that I don't get.

ReadOnlyArrayGattCharacteristic<uint8_t, sizeof(readValue)> readChar(readCharUUID, readValue);

In this line of code, how is the < and > used? Even if I want to google this, I can't search it properly because google will think < > as special characters. Could someone give me a keyword to start on?

You probably would want to read more on the documentation here.

Where <inbrackets> means a template<typename T , unsigned NUM_ELEMENTS>. According to the ISO C++ (https://isocpp.org/wiki/faq/templates)

A template is a cookie-cutter that specifies how to cut cookies that all look pretty much the same (although the cookies can be made of various kinds of dough, they’ll all have the same basic shape). In the same way, a class template is a cookie cutter for a description of how to build a family of classes that all look basically the same, and a function template describes how to build a family of similar looking functions.

Class templates are often used to build type safe containers (although this only scratches the surface for how they can be used).

For example

Consider a container class Array that acts like an array of integers:

// This would go into a header file such as "Array.h"
class Array {
  Array(int len=10)                  : len_(len), data_(new int[len]) { }
 ~Array()                            { delete[] data_; }
  int len() const                    { return len_;     }
  const int& operator[](int i) const { return data_[check(i)]; }  // Subscript operators often come in pairs
  int&       operator[](int i)       { return data_[check(i)]; }  // Subscript operators often come in pairs
  Array(const Array&);
  Array& operator= (const Array&);
  int  len_;
  int* data_;
  int  check(int i) const
      if (i < 0 || i >= len_)
        throw BoundsViol("Array", i, len_);
      return i;

Repeating the above over and over for Array of float, of char, of std::string, of Array-of-std::string, etc, would become tedious. Instead, you add the template<typename T> before the class definition (the T can be any identifier you want, T is just the most commonly used one, especially in examples). Then, instead of using int or float or char where referring to the data type, you use T instead. Also, instead of just referring to the class as Array, it’s Array<T> when referring to the template, or Array<int>, Array<float>, etc. when referring to a specific instantiation.

// This would go into a header file such as "Array.h"
template<typename T>
class Array {
  Array(int len=10)                : len_(len), data_(new T[len]) { }
 ~Array()                          { delete[] data_; }
  int len() const                  { return len_;     }
  const T& operator[](int i) const { return data_[check(i)]; }
  T&       operator[](int i)       { return data_[check(i)]; }
  Array(const Array<T>&);
  Array<T>& operator= (const Array<T>&);
  Array<T>& operator= (Array<T>&&);
  int len_;
  T*  data_;
  int check(int i) const {
    assert(i >= 0 && i < len_);
    return i;

Read this book it will help http://www.amazon.com/Template-Metaprogramming-Concepts-Techniques-Beyond/dp/0321227255