C++ Templates

David Vandevoorde, Nicolai M. Josuttis

Mentioned 50

With the greatly increased use of templates, there is a real need in the C++ community for this information. This book is the next C++ classic, acting as both a complete reference as well as a tutorial. It emphasizes the practical use of templates, and includes real-world examples.

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

Beginner

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]

Intermediate

  • 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]


Advanced

  • 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.

What is a smart pointer and when should I use one?

Smart pointer is a pointer-like type with some additional functionality, e.g. automatic memory deallocation, reference counting etc.

Small intro is available on page Smart Pointers - What, Why, Which?.

One of the simple smart-pointer type is std::auto_ptr (chapter 20.4.5 of C++ standard), which allows to deallocate memory automatically when it out of scope and which is more robust than simple pointer usage when exceptions are thrown, although less flexible.

Another convenient type is boost::shared_ptr which implements reference counting and automatically deallocates memory when no references to object remains. This helps avoiding memory leaks and is easy to use to implement RAII.

Subject is covered in depth in book "C++ Templates: The Complete Guide" by David Vandevoorde, Nicolai M. Josuttis, chapter Chapter 20. Smart Pointers. Some topics covered:

I'm looking for the rules involving passing C++ templates functions as arguments.

This is supported by C++ as shown by an example here:

#include <iostream>

void add1(int &v)
{
  v+=1;
}

void add2(int &v)
{
  v+=2;
}

template <void (*T)(int &)>
void doOperation()
{
  int temp=0;
  T(temp);
  std::cout << "Result is " << temp << std::endl;
}

int main()
{
  doOperation<add1>();
  doOperation<add2>();
}

Learning about this technique is difficult, however. Googling for "function as a template argument" doesn't lead to much. And the classic C++ Templates The Complete Guide surprisingly also doesn't discuss it (at least not from my search).

The questions I have are whether this is valid C++ (or just some widely supported extension).

Also, is there a way to allow a functor with the same signature to be used interchangeably with explicit functions during this kind of template invocation?

The following does not work in the above program, at least in Visual C++, because the syntax is obviously wrong. It'd be nice to be able to switch out a function for a functor and vice versa, similar to the way you can pass a function pointer or functor to the std::sort algorithm if you want to define a custom comparison operation.

   struct add3 {
      void operator() (int &v) {v+=3;}
   };
...

    doOperation<add3>();

Pointers to a web link or two, or a page in the C++ Templates book would be appreciated!

Yes, it is valid.

As for making it work with functors as well, the usual solution is something like this instead:

template <typename F>
void doOperation(F f)
{
  int temp=0;
  f(temp);
  std::cout << "Result is " << temp << std::endl;
}

which can now be called as either:

doOperation(add2);
doOperation(add3());

The problem with this is that if it makes it tricky for the compiler to inline the call to add2, since all the compiler knows is that a function pointer type void (*)(int &) is being passed to doOperation. (But add3, being a functor, can be inlined easily. Here, the compiler knows that an object of type add3 is passed to the function, which means that the function to call is add3::operator(), and not just some unknown function pointer.)

No C++ love when it comes to the "hidden features of" line of questions? Figured I would throw it out there. What are some of the hidden features of C++?

Defining ordinary friend functions in class templates needs special attention:

template <typename T> 
class Creator { 
    friend void appear() {  // a new function ::appear(), but it doesn't 
        …                   // exist until Creator is instantiated 
    } 
};
Creator<void> miracle;  // ::appear() is created at this point 
Creator<double> oops;   // ERROR: ::appear() is created a second time! 

In this example, two different instantiations create two identical definitions—a direct violation of the ODR

We must therefore make sure the template parameters of the class template appear in the type of any friend function defined in that template (unless we want to prevent more than one instantiation of a class template in a particular file, but this is rather unlikely). Let's apply this to a variation of our previous example:

template <typename T> 
class Creator { 
    friend void feed(Creator<T>*){  // every T generates a different 
        …                           // function ::feed() 
    } 
}; 

Creator<void> one;     // generates ::feed(Creator<void>*) 
Creator<double> two;   // generates ::feed(Creator<double>*) 

Disclaimer: I have pasted this section from C++ Templates: The Complete Guide / Section 8.4

There is no hidden features, but the language C++ is very powerful and frequently even developers of standard couldn't imagine what C++ can be used for.

Actually from simple enough language construction you can write something very powerful. A lot of such things are available at www.boost.org as an examples (and http://www.boost.org/doc/libs/1_36_0/doc/html/lambda.html among them).

To understand the way how simple language constuction can be combined to something powerful it is good to read "C++ Templates: The Complete Guide" by David Vandevoorde, Nicolai M. Josuttis and really magic book "Modern C++ Design ... " by Andrei Alexandrescu.

And finally, it is difficult to learn C++, you should try to fill it ;)

I've been playing with clang a while, and I stumbled upon "test/SemaTemplate/dependent-template-recover.cpp" (in the clang distribution) which is supposed to provide hints to recover from a template error.

The whole thing can be easily stripped down to a minimal example:

template<typename T, typename U, int N> struct X {
    void f(T* t)
    {
        // expected-error{{use 'template' keyword to treat 'f0' as a dependent template name}}
        t->f0<U>();
    }
};

The error message yielded by clang:

tpl.cpp:6:13: error: use 'template' keyword to treat 'f0' as a dependent template name
         t->f0<U>();
            ^
            template 
1 error generated.

... But I have a hard time understanding where exactly one is supposed to insert the template keyword to have the code to be syntactically correct?

Excerpt from C++ Templates

The .template Construct A very similar problem was discovered after the introduction of typename. Consider the following example using the standard bitset type:

template<int N> 
void printBitset (std::bitset<N> const& bs) 
{ 
    std::cout << bs.template to_string<char,char_traits<char>, 
                                       allocator<char> >(); 
} 

The strange construct in this example is .template. Without that extra use of template, the compiler does not know that the less-than token (<) that follows is not really "less than" but the beginning of a template argument list. Note that this is a problem only if the construct before the period depends on a template parameter. In our example, the parameter bs depends on the template parameter N.

In conclusion, the .template notation (and similar notations such as ->template) should be used only inside templates and only if they follow something that depends on a template parameter.

I've been programming in C++ for a few years, and I've used STL quite a bit and have created my own template classes a few times to see how it's done.

Now I'm trying to integrate templates deeper into my OO design, and a nagging thought keeps coming back to me: They're just a macros, really... You could implement (rather UGLY) auto_ptrs using #defines, if you really wanted to.

This way of thinking about templates helps me understand how my code will actually work, but I feel that I must be missing the point somehow. Macros are meant evil incarnate, yet "template metaprogramming" is all the rage.

So, what ARE the real distinctions? and how can templates avoid the dangers that #define leads you into, like

  • Inscrutable compiler errors in places where you don't expect them?
  • Code bloat?
  • Difficulty in tracing code?
  • Setting Debugger Breakpoints?

Templates can do a lot more than the macro preprocessor is able to do.

E.g. there are template specializations: If this template is instanciated with this type or constant, than do not use the default implementation, but this one here...

... templates can enforce that some parameters are of the same type, etc...


Here are some sources You might want to look at:

  • C++ templates by Vandervoorde and Jossutis. This is the best and most complete book about templates I know.
  • The boost library consists almost entirely of template definitions.

Reading this question made me wonder: is there a technical reason for disallowing class templates overloads?

By overloading, I mean having several templates with the same names, but different parameters, for instance

template <typename T>
struct Foo {};

template <typename T1, typename T2>
struct Foo {};

template <unsigned int N>
struct Foo {};

The compiler manages to handle overloaded functions and function templates, wouldn't it be possible to apply the same techniques (e.g. name mangling) to class templates?

At first, I thought that perhaps that would cause some ambiguity issues when taking the template identifier alone, but the only time this can happen is when passing it as a template template argument, so the type of the parameter could be used to choose the appropriate overload:

template <template <typename> class T>
void A {};

template <template <unsigned int> class T>
void B {};

A<Foo> a; // resolves to Foo<T>
B<Foo> b; // resolves to Foo<N>

Do you think such feature could be useful? Is there some "good" (i.e. technical) reasons why this is not possible in current C++?

Section 12.5 from Templates the Complete Guide (Amazon) contains this quote:

You may legitimately wonder why only class templates can be partially specialized. The reasons are mostly historical. It is probably possible to define the same mechanism for function templates (see Chapter 13).

In some ways the effect of overloading function templates is similar, but there are also some subtle differences. These differences are mostly related to the fact that the primary template needs to be looked up when a use is encountered. The specializations are considered only afterward, to determine which implementation should be used.

In contrast, all overloaded function templates must be brought into an overload set by looking them up, and they may come from different namespaces or classes. This increases the likelihood of unintentionally overloading a template name somewhat.

Conversely, it is also imaginable to allow a form of overloading of class templates. Here is an example:

// invalid overloading of class templates
template<typename T1, typename T2> class Pair; 
template<int N1, int N2> class Pair; 

However, there doesn't seem to be a pressing need for such a mechanism.

Furthermore, the Design and Evolution of C++ (Amazon) contains this quote in section 15.10.3

I therefore concluded that we needed a mechanism for "specializing templates. This could be done either by accepting general overloading or by some more specific mechanism. I chose a specific mechanism because I thought I was primarily addressing irregularities caused by irregularities in C and because suggestions of overloading invariably creates a howl of protests. I was trying to be cautious and conservative; I now consider that a mistake. Specialization as originally defined was a restricted and anomalous form of overloading that fitted poorly with the rest of the language.

Bold emphasis mine. I interpret this as saying that function overload resolution is more difficult to implement (and get right by users) than class specialization. So probably no real technical obstacles (similary for function template partial specialization) but an historical accident.

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'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.

Downsides:

  • 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:

In a discussion on another question, I was given an example where apparently linkage of an identifier affected its usability in a constant expression:

extern char const a[] = "Alpha";
char constexpr b[] = "Beta";
char const g[] = "Gamma";

template <const char *> void foo() {}

auto main()
    -> int
{
    foo<a>();     // Compiles
    foo<b>();     // Compiles
    foo<g>();     // Doesn't compile
}

The error from the last (with GCC) is:

test.cc: In function 'int main()':
test.cc:12:13: error: the value of 'g' is not usable in a constant expression
         foo<g>();     // Doesn't compile
             ^
test.cc:3:16: note: 'g' was not declared 'constexpr'
     char const g[] = "Gamma";
                ^

I may have missed the significance of the example in the earlier discussion, because I believed that it could not have been just linkage which differentiated foo<a> from foo<g> - however, I have begun to doubt that position.

  1. Is it really the linkage, or is it some other attribute granted by extern, that allows foo<a>()?
  2. What is the rationale for allowing foo<a>() but not foo<g>()? In particular, if it is determined by linkage, why should internal linkage cause a variable not to be usable as a constant expression when the same variable declared extern would be usable?
  3. It was suggested that the question of the symbol being visible (or not) to the linker is relevant here. To me, it seems that the fact the foo<b> variant is still allowed even when static is added disproves this - or am I mistaken?
  4. (The difference between foo<b>() and foo<g>() is adequately covered by other questions, I think).

This is a weird coincidence. I was just reading about this in C++ Templates just last night. When using a pointer as a template non-type parameter, it is the address contained in the pointer rather than the value pointed-to by the pointer that is the constant substituted as the template argument. Thus, the address must be knowable at compile time and unique across all compilation units to avoid ODR violations. This is true of constexpr and extern variables, but not those with file or global linkage. Here's an example.

static char const foo[] = "Hello";
char const bar[] = "Hello";
constexpr char const baz[] = "Hello";
extern char const qux[] = "Hello";

template <char const*>
struct my_struct{};

int main() {
    my_struct<foo> f;       // ERROR: Address is unique, but not known until runtime
    my_struct<bar> b;       // ERROR: Address may or may not be unique (ODR violation) and not known until runtime
    my_struct<baz> bz;      // OK: constexpr
    my_struct<qux> q;       // OK: extern
}
struct Bar {
    template<typename>
    void baz() {
    }
};

template<typename>
struct Foo {
    Bar bar;

    Foo() {
        bar.baz<int>();
    }
};

int main() {
    return 0;
}

This code compiles fine (in GCC 4.7), but if I prefix the call to bar.baz<int>() with this->, baz becomes a dependent name that needs disambiguating with template.

bar.baz<int>(); // OK
this->bar.baz<int>(); // error
this->bar.template baz<int>(); // OK

Surely this->bar can only refer to Bar bar, whose member baz is clearly a template? Why does the addition of this-> make this code ambiguous to the compiler?

p.s. Originally, bar was a data member of a base class template which needed disambiguating with this->, but I have simplified the example for the purpose of this question.

Short summary

This is just the way the current C++11 rules are: this->bar.baz<int>() introduces a dependent name not in the current instantiation context that requires disambiguation with the template keyword, even though it is very hard to come up with an actual example of a competing parse that change the semantics of the expression this->bar.baz<int>().

Parsing ambiguity from angle brackets

First: why in general is there a need for template?

When a C++ compiler encounters an expression f<g>(0), it can interpret this either as "call the function template f for template argument g and function argument 0 and evaluate the result" or it can mean "make the comparison (f<g)>(0) for names f and g and constant 0." Without further information it cannot make this decision. This is an unfortunate consequence of the choice of angle brackets for template arguments.

In many (most) cases, the compiler does have enough context to decide whether a template expression or a comparison is being parsed. However, when a so-called dependent name (essentially a name that is explicitly or implicitly dependent on a template parameter of the current scope) is encountered, another language subtlety comes into play.

Two-phase name lookup

Because a name dependent on a template could change its meaning (e.g. through specializations) when a template is being instantiated for a concrete type, name lookup of dependent names is done in two phases (quote from C++ Templates the Complete Guide):

During the first phase, nondependent names are looked up while the template is being parsed using both the ordinary lookup rules and, if applicable, the rules for argument-dependent lookup (ADL). Unqualified dependent names (which are dependent because they look like the name of a function in a function call with dependent arguments) are also looked up that way, but the result of the lookup is not considered complete until an additional lookup is performed when the template is instantiated.

During the second phase, which occurs when templates are instantiated at a point called the point of instantiation (POI), dependent qualified names are looked up (with the template parameters replaced with the template arguments for that specific instantiation), and an additional ADL is performed for the unqualified dependent names.

Why this-> makes your code different

Using this-> inside a class template introduces a dependent name and triggers two-phase name lookup. In that case, the rule cited by @40two comes into play. The point is that the ADL at the 2nd phase can bring in new names from explicit specializations that redefine the meaning of your bar and baz and it could conceivably change the meaning of this->bar.baz<int>(0) to a comparison rather than a function template call.

Granted, for non-type template arguments such as this->bar.another_baz<0>() this would be more likely than for a type template parameter. In this related Q&A a similar discussion arose whether one could find a syntactic valid form that changes the meaning of this->f<int>() vs this->template f<int>(0), without a clear conclusion.

Note that C++11 already relaxes the rule for template disambiguation compared to C++98. Under the current rules this->f<int>() for a template<class> f() inside Foo would not require template because it is in the so-called current instantiation. See this answer from the canonical Q&A for this topic for more details

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).

Section 4.3 of C++ Templates states 'Not being able to use floating-point literals (and simple constant floating-point expressions) as template arguments has historical reasons.'

Similarly,

$14.1/7 states - "A non-type template-parameter shall not be declared to have floating point, class, or void type. [ Example:

template<double d> class X; // error
template<double* pd> class Y; // OK
template<double& rd> class Z; // OK"
  1. What is the historical reason that is being talked about in the book in the above quote?

  2. Looking at why Y and Z are valid but not X, is the whole challenge related to having non type template parameters of floating type got to do anything with pointers/references?

  3. Why template non type parameters can not be of class type?

I have written a small library that use a lot of C++11 metaprogramming techniques and CRTP, and it compiles well with g++ 4.7.2

Now, I try to compile it with Intel icpc 13.0.0.079 and it generates several hundreds of errors. So I try to isolate the problems one after another.

So, first, consider this code, that compiles with no problem under g++ 4.7.2

#include <iostream>

template<template<typename> class Crtp, typename Type>
struct Base {};

template<typename Type>
struct Derived : public Base<Derived, Type>
{
    Derived(): Base<Derived, Type>() {;}
};

int main()
{
    Derived<int> x;
    return 0;
}

Both icpc and clang fail to compile this code:

test_crtp.cpp(26): error: type "Derived<Type>::Derived" is not a class template
      Derived(): Base<Derived, Type>() {;}
                      ^

test_crtp.cpp(26): error: "Base" is not a nonstatic data member or base class of class "Derived<int>"
      Derived(): Base<Derived, Type>() {;}
                 ^
          detected during instantiation of "Derived<Type>::Derived() [with Type=int]" at line 31

compilation aborted for test_crtp.cpp (code 2)

So is it a bug in intel and clang, or in g++ ? If it's in intel and clang, do you think that it will be solved in a future version ?

In section 9.2.3 of C++ Template the Complete Guide (Amazon), there is a discussion on Injected Class Names. To quote:

Class templates also have injected class names. However, they're stranger than ordinary injected class names: They can be followed by template arguments (in which case they are injected class template names), but if they are not followed by template arguments they represent the class with its parameters as its arguments (or, for a partial specialization, its specialization arguments). This explains the following situation:

template<template<typename> class TT> 
class X {};

template<typename T> 
class C 
{
    Ca;        // OK: same as ''C<T> a;''
    C<void> b; // OK
    X<C> c;    // ERROR: C without a template argument list
               // does not denote a template
    X<::C> d;  // ERROR: <: is an alternative token for [
    X< ::C> e; // OK: the space between < and :: is required
}

Note how the unqualified name refers to the injected name and is not considered the name of the template if it is not followed by a list of template arguments. To compensate, we can force the name of the template to be found by using the file scope qualifier ::. This works, but we must then be careful not to create a so-called digraph token <:, which is interpreted as a left bracket. Although relatively rare, such errors result in perplexing diagnostics.

So what happens in your code is that Base<Derived, Type> is being interpreted as Base<Derived<Type>, Type> which is ill-formed. Therefore you need to use the scope qualifier :: with a space between the < to avoid a digraph.

Consider the following small code fragment:

#include <iostream> 

template<class T> 
int test(); 

int main() 
{     
    std::cout << test<int>() << "\n"; 
} 

// POI for test<int>() should be right here      

template<class T> 
int test() 
{ 
    return 0; 
}

Live Example that compiles and prints 0 for both Clang and g++.

Here's the draft Standard quote on the point of instantiation of function templates

14.6.4.1 Point of instantiation [temp.point]

1 For a function template specialization, a member function template specialization, or a specialization for a member function or static data member of a class template, if the specialization is implicitly instantiated because it is referenced from within another template specialization and the context from which it is referenced depends on a template parameter, the point of instantiation of the specialization is the point of instantiation of the enclosing specialization. Otherwise, the point of instantiation for such a specialization immediately follows the namespace scope declaration or definition that refers to the specialization.

Vandevoorde and Josuttis have the following to say about this:

In practice, most compilers delay the actual instantiation of noninline function templates to the end of the translation unit. This effectively moves the POIs of the corresponding template specializations to the end of the translation unit. The intention of the C++ language designers was for this to be a valid implementation technique, but the standard does not make this clear.

Question: are Clang/g++ non-conforming because they delay the POI to the end of the translation unit?

Core Working Group defect report 993 was created to address this issue:

993. Freedom to perform instantiation at the end of the translation unit

Section: 14.6.4.1 [temp.point] Status: C++11 Submitter: John Spicer Date: 6 March, 2009
[Voted into the WP at the March, 2011 meeting.]

The intent is that it is a permissible implementation technique to do template instantiation at the end of a translation unit rather than at an actual point of instantiation. This idea is not reflected in the current rules, however.

Proposed resolution (January, 2011):

Change 14.6.4.1 [temp.point] paragraph 7 as follows:

A specialization for a function template, a member function template, or of a member function or static data member of a class template may have multiple points of instantiations within a translation unit, and in addition to the points of instantiation described above, for any such specialization that has a point of instantiation within the translation unit, the end of the translation unit is also considered a point of instantiation. A specialization for a class template...

Paragraph 14.6.4.1/7 in C++11 is 14.6.4.1/8 in N3936:

A specialization for a function template, a member function template, or of a member function or static data member of a class template may have multiple points of instantiations within a translation unit, and in addition to the points of instantiation described above, for any such specialization that has a point of instantiation within the translation unit, the end of the translation unit is also considered a point of instantiation. A specialization for a class template has at most one point of instantiation within a translation unit. A specialization for any template may have points of instantiation in multiple translation units. If two different points of instantiation give a template specialization different meanings according to the one definition rule (3.2), the program is ill-formed, no diagnostic required.

So yes, it is allowable for implementations to delay the point of instantiation of templates to the end of the translation unit.

Given the code below, why is the foo(T*) function selected ?

If I remove it (the foo(T*)) the code still compiles and works correctly, but G++ v4.4.0 (and probably other compilers as well) will generate two foo() functions: one for char[4] and one for char[7].

#include <iostream>
using namespace std;

template< typename T >
void foo( const T& )
{
    cout << "foo(const T&)" << endl;
}

template< typename T >
void foo( T* )
{
    cout << "foo(T*)" << endl;
}

int main()
{
    foo( "bar" );
    foo( "foobar" );
    return 0;
}

Based on overload resolution rules (Appendix B of C++ Templates: The Complete Guide has a good overview), string literals (const char []) are closer to T* than T&, because the compiler makes no distinction between char[] and char*, so T* is the closest match (const T* would be an exact match).

In fact, if you could add:

template<typename T>
void foo(const T[] a)

(which you can't), your compiler would tell you that this function is a redefinition of:

template<typename T>
void foo(const T* a)

What are good introductions to the creation of C++ expression template systems? I would like to express arithmetic on user defined types while avoiding temporary values (which may be large), and to learn how to do this directly rather than applying an existing library.

I have found Todd Veldhuizen's original paper and an example from the Josuttis C++ Templates book, and an article by Kreft & Langer. It is mentioned in Lecture 6 of a course on Modern C++, referring back to Josuttis.The POOMA library background introduces expression templates nicely.

I am looking for simple, clear expositions.

You should get a copy of C++ Templates: The Complete Guide.

The code example to which you link doesn't have the accompanying text, which is quite helpful (the chapter on expression templates is 22 pages long). Without the text, all you have is code without any comments or explanation as to what it does and how and why it does it.

I remember seing something like this being done:

template <ListOfTypenames>
class X : public ListOfTypenames {};

that is, X inherits from a variable length list of typenames passed as the template arguments. This code is hypothetical, of course.

I can't find any reference for this, though. Is it possible? Is it C++0x?

Variable number of templates is part of the next C++ standard. However, you can get a taste of it if you're using GCC (from version 4.3). Here's a list of available C++0x features in GCC. You're looking for Variadic Templates.

By the way, if you need a formal reference on how to achieve the inheritance mechanism as described by Earwicker, it's on the book C++ Templates.

I made the following program

#include <iostream>
#include <typeinfo>
template<class T>
struct Class
{
    template<class U>
    void display(){

        std::cout<<typeid(U).name()<<std::endl;
        return ;
    }

};


template<class T,class U>
void func(Class<T>k)
{
    k.display<U>(); 

}

int main()
{
    Class<int> d;
    func<int,double>(d);
}

The above program doesn not compile because display() is a template member function so a qualification of .template before display() must be done. Am I right?

But when I made the following program

#include <iostream>
#include <typeinfo>

template<typename T>
class myClass
{
    T dummy;
    /*******/
public:
    template<typename U>
    void func(myClass<U> obj);

};

template<typename T>
template<typename U>

void myClass<T>::func(myClass<U> obj)
{
    std::cout<<typeid(obj).name()<<std::endl;
}
template<class T,class U>
void func2(myClass<T>k)
{
    k.template func<U>(k); //even it does not compile

}
int main()
{
    myClass<char> d;
    func2<char,int>(d);
    std::cin.get();
}

Why k.func<char>(k); does not compile even after giving a .template construct?

Section 5.1 of C++ Templates explains this construct in detail

The below function has a problem

template<class T,class U> 
void func2(myClass<T> k) 
{ 
    k.template func<U>(k); //even it does not compile 

} 

Here T = char and U = int

myclass<char>::func<int>(myclass<char>) 

is being called. However such a function does not exist

Even though in normal circumstances 'char' is convertible to 'int', this does not hold good for explicitly specified template arguments

I am trying to understand the overload resolution rules in the following case:

template<typename T>
void f(const T& x) { 
    std::cout << __PRETTY_FUNCTION__ << std::endl; //-
}

template<typename T>
void f(T& x) { // <> Überladung Variante 2
    std::cout << __PRETTY_FUNCTION__ << std::endl; //-
}

int main()
{
    int e1 = 0;
    f(e1);

    const int e2 = 0;
    f(e2); 
}

The output is:

void f(T &) [T = int]
void f(const T &) [T = int]

As I understand in the first call to f(e1) leads to the viable functions

void f(const int&)
void f(int&)

from which the first one is chosen because the const-qualification hasn't to be removed.

The second call to f(e2) leads to the type deductions / viable functions

void f(const int&); // T -> int from first template overload 
void f(const int&); // T -> const int from second overload

and the output shows that the first overload is choosen.

But why?

When performing type deduction with references, the const-ness (more specifically CV-ness) is not removed. So in your case the compiler has 2 overloads to choose from:

void f(const T &)
void f(T &)

The compiler then performs "pattern matching" when choosing the overload for your const int e2 = 0; argument. The first const overload is a better match (more specialized), as the second one would require deducing T as const int, which adds something (i.e. const-ness).

The rules for template type deductions are not super straightforward, so if you want to learn all nitty-gritty details about templates, I highly recommend the book

C++ Templates: The Complete Guide by David Vandevoorde and Nicolai M. Josuttis.

It's pre C++11, but nevertheless it tells you everything you can think of.

PS: you must make a differentiation between instantiation and template type deduction. The type deduction happens first, then an instantiation follows. So in your case you don't have 2 ambiguous instantiations as you may have thought initially.

I currently use C for numerical computations. I've heard that using C++ Expression Templates is better for scientific computing. What are C++ Expression Templates in simple terms?

  1. Are there books around that discuss numerical methods/computations using C++ Expression Templates?

  2. In what way, C++ Expression Templates are better than using pure C?

What are C++ Expression Templates in simple terms?

Expression templates are a category of C++ template meta programming which delays evaluation of subexpressions until the full expression is known, so that optimizations (especially the elimination of temporaries) can be applied.

Are there books around that discuss numerical methods/computations using C++ Expression Templates?

I believe ET's were invented by Todd Veldhuizen who published a paper on it 15 years ago. (It seems that many older links to it are dead by now, but currently here is a version of it.) Some material about it is in David Vandevoorde's and Nicolai Josuttis' C++ Templates: The Complete Guide.

In what way, C++ Expression Templates are better than using pure C?

They allow you to write your code in an expressive high level way without losing performance. For example,

void f(const my_array<double> a1, const my_array<double> a2) 
{ 
  my_array<double> a3 = 1.2 * a1 + a1 * a2; 
  // ..
}

can be optimized all the way down to

for( my_array<double>::size_type idx=0; idx<a1.size(); ++idx ) 
  a3[idx] = 1.2*a1[idx] + a1[idx]*a2[idx]; 

which is faster, but harder to understand.

Is there some utility which would allow me to inspect template instantiation? my compiler is g++ or Intel.

Specific points I would like:

  • Step by step instantiation.
  • Instantiation backtrace (can hack this by crashing compiler. Better method?)
  • Inspection of template parameters.

@gf helpd me with simple type printing, C++ template name pretty print.

However I am getting into boost phoenix and template level makes it very hard to understand what is going on and I would like intelligent solution

also, if you have some techniques inspecting template instantiation, can you please share them.

Thanks

With templates we simply don't have clean output facilities and there are no compilers i know of that allow you to directly view template instantiations. The closest i found regarding metaprogram debugging was a paper on Templight.

For now the best utilities seem to be:

I wrote a simple class for the moving average which can be used with an AVR.

template<typename T, typename Tsum = int32_t>
class MovingAverage { ... }

But now I want to specialize this class for float without copying and pasting the whole class body and change all T and Tsum to float and that I do not need to use two template parameters. Tsum is the type for the 'sum' variable where all passed values of type T were summed up. If T is 'uint8_t' it is a good idea to use 'uint32_t' for the sum, but for float or double there is no need to use a datatype with higher precision, so I want only one parameter for this purpose. I thought it could work this way:

typedef MovingAverage<float, float> MovingAverage<float>

or this way:

template<>
class MovingAverage<float> : public MovingAverage<float, float> {};

But I was wrong and I found only solutions where I have to write my code twice.

Is there a way to write the class only once and then specialize it this way I prefer? Thanks in advance!

You could write a simple traits class

// general version
template<typename T>
struct sum_type
{
    typedef int32_t type;
};

// specialized version
template<>
struct sum_type<float>
{
    typedef float type;
};

// repeat for double, the solution from @DanielFrey is even more sophisticated 
// as it specializes all floating point types in one sweep.

and then extract this type in your class template

template<typename T, typename Tsum = typename sum_type<T>::type>
//                                   ^^^^^^^^ <-- dependent type disambiguation
class MovingAverage { ... };

Note that this only works if your MovingAverage has a regularly parameterized implementation. If you are actually doing something special for float (e.g. rewrite expressions to take care of the non-associative character of floating point arithmetic), then you need to do more work.

If you are serious about working with C++ templates, run -not walk- to the nearest bookstore and get the book C++ Templates: The Complete Guide. Section 15.1 has a 15+ page discussion of defining a generic accumulate class template.

The book C++ Templates : The Complete Guide has an example on page 275 that I'm having trouble wrapping my head around.

Quoting excerpts from the book...

template <typename T>
class Promotion<T,T> {
  public:
    typdef T ResultT;
};

template<typename T1, typename T2>
class Promotion<Array<T1>, Array<T2> > {
  public:
    typedef Array<typename Promotion<T1,T2>::ResultT> ResultT;
};

template<typename T>
class Promotion<Array<T>, Array<T> > {
  public:
    typedef Array<typename Promotion<T,T>::ResultT> ResultT;
};

Unfortunately, the partial specialization Promotion<Array<T1>, Array<T2> > is neither more nor less specialized than the partial specialization Promotion<T,T>. To avoid template selection ambiguity, the last partial specialization was added. It is more specialized than either of the previous two partial specializations.

Why are the first two templates ambiguous, and why does the last template solve the ambiguity issue? When I try to apply the rules I either can't figure out how it comes up with an ambiguity, or if I think I have a way for it to happen I don't know why the last template solves the problem.

Maybe your confusion stems from how the relation "is more specialised than" works. It's a partial order, not a total order -- that means that given 2 template specialisations, it's not always the case that one is more specialised than the other.

Anon's comment is right: Suppose that 3rd specialisation didn't exist, and later in your code you had:

Promotion<Array<double>, Array<double> > foo;

(Of course you probably wouldn't actually create a variable of this empty struct type, but this is just the simplest way to force its instantiation.)

Given this declaration of foo, which of the 1st 2 specialisations would be picked?

  • Specialisation 1 applies, with T = Array<double>.
  • Specialisation 2 applies, with T1 = double, T2 = double.

Both specialisations are applicable, so we need to determine which "is more specialised than" the other, and pick that one. How? We will say that X is more specialised than Y if it is at least as specialised as Y, but Y is not at least as specialised as X. Although it seems like this is just dancing around the problem, there is a clever rule that we can use to answer this new question:

X is at least as specialised as Y if, regardless of what types we assign to the template parameters of X, the resulting type could always be matched by Y.

Note that we forget about the particular types involved in the current instantiation (in this case, double) -- the "is at least as specialised as" relation is a property of the partial specialisations themselves, and doesn't depend on particular instantiations.

Can specialisation 1 always be matched by specialisation 2? The process is a bit like algebra. We require that for any type T, we can find types T1 and T2 such that:

Promotion<Array<T1>, Array<T2> > = Promotion<T, T>

This implies:

Array<T1> = T
Array<T2> = T

So the answer is no. Looking at just the first implied result, given any type T, in general it's not possible to find a type T1 such that Array<T1> is the same type as T. (It would work if T happened to be Array<long>, but not if T is int or char* or most other types.)

What about the other way around? Can specialisation 2 always be matched by specialisation 1? We require that for any types T1 and T2, we can find a type T such that:

Promotion<T, T> = Promotion<Array<T1>, Array<T2> >

Implying:

T = Array<T1>
T = Array<T2>

So the answer is again no. Given any type T1, it's always possible to find a type T such that T is the same type as Array<T1> -- just literally set T = Array<T1>. But in general the other type T2 is not constrained to be the same as T1, and if it's not (e.g. if T1 = bool but T2 = float) then it will not be possible to find a type T that is the same as both Array<T1> and Array<T2>. So in general, it's not possible to find such a type T.

In this case, not only is neither specialisation more specialised than the other, neither is even as specialised as the other. As a result, if the need arises to instantiate this template class and both specialisations match -- as it does in the example Anon gave -- there is no way to choose a "best" one.

I have the following code:

Some functions:

A::A(int i_a) {cout<<"int Ctor\n";}          //conversion constructor

void h(double d) {cout<<"double param\n";}   //f1
void h(A a) {cout<<"A param\n";}             //f2

In the main function:

h(1);

The function that h(1) calls is f1.

My question is why does it choose to call that. 1 is an int and therefore requires implicit conversion to double. It could just as easily convert the int into an A using the conversion constructor defined above. Why don't I get an error? What are the precedence rules with casting?


N.b. I've posted above the code that I think will be necessary to answer the question, but below I'm posting the entire code:

 #include <iostream>
 using namespace std;
 class B;
 class A {
 public:
 explicit A(const B&) {cout<<"Ctor through B\n";}
 A() {cout<<"Default Ctor\n";}
 A(int i_a) {cout<<"int Ctor\n";}
 operator int() {cout<<"A => int\n"; return 2;}
 };
 class B {
 public:
 operator A() const {cout<<"B => A\n"; A a; return a;}
 };
 void h(double d) {cout<<"double param\n";}
 void h(A a) {cout<<"A param\n";}
 void f(const A& a)
 {
 cout<<"f function\n";
 //Without the const it will never try to convert
 }
 void main()
 {
 B b;
 cout <<"-----------------\n";
 f(b);
 cout <<"-----------------\n";
 h(1);
 }

When overload resolution is performed to select the best candidate out of all viable overloads - the compiler ranks all the conversion sequences for each argument for each candidate. For a function to win (be selected as the best candidate), its conversion ranks for each argument have to be better than or equal to every other function's conversion ranks for that argument AND at least one conversion rank has to be better than all the other function's conversion ranks for a certain argument.

The user defined conversion (which uses either a constructor or a cast operator) has one of the worst possible ranks (only the ellipsis has a worse rank). The integral-floating conversion has a better rank (see below for a list of the rankings).

Thus, the compiler prefers converting an int -> double (using a standard conversion) than converting an int -> A (using a user defined conversion), and therefore it selects f1.

Edit: Although "Overload resolution" works in the background and most of the time does exactly what you would expect (i.e. most programmers won't need to delve into the technicalities) - if you do want to go deeper (but be warned that some of the darker corners of overload resolution are considered to be one of the trickiest aspects for compiler writers to get exactly right in a C++ compiler) refer to the excellent C++ Templates: The Complete Guide by David Vandevoorde and Nicolai M. Josuttis which provides, in appendix B, one of the best introductions to the machinery behind overload resolution that I have read.

Here is an excerpt from B.2:

Overload resolution ranks the viable candidate functions by comparing how each argument of the call matches the corresponding parameter of the candidates. For one candidate to be considered better than another, the better candidate cannot have any of its parameters be a worse match than the corresponding parameter in the other candidate. ...

Given this first principle, we are left with specifying how well a given argument matches the corresponding parameter of a viable candidate. As a first approximation we can rank the possible matches as follows (from best to worst):

Perfect match. The parameter has the type of the expression, or it has a type that is a reference to the type of the expression (possibly with added const and/or volatile qualifiers).

Match with minor adjustments. This includes, for example, the decay of an array variable to a pointer to its first element, or the addition of const to match an argument of type int** to a parameter of type int const* const*.

Match with promotion. Promotion is a kind of implicit conversion that includes the conversion of small integral types (such as bool, char, short, and sometimes enumerations) to int, unsigned int, long or unsigned long, and the conversion of float to double.

Match with standard conversions only. This includes any sort of standard conversion (such as int to float) but excludes the implicit call to a conversion operator or a converting constructor.

Match with user-defined conversions. This allows any kind of implicit conversion.

Match with ellipsis. An ellipsis parameter can match almost any type (but non-POD class types result in undefined behavior).

But that's just the beginning - if you are intrigued - I urge you to read the book and then the relevant portions of the standard :)

Today I see the following code in stl_pair.h:

#ifdef __STL_FUNCTION_TMPL_PARTIAL_ORDER

template <class _T1, class _T2>
inline bool operator!=(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y) {
  return !(__x == __y);
}

template <class _T1, class _T2>
inline bool operator>(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y) {
  return __y < __x;
}

#endif /* __STL_FUNCTION_TMPL_PARTIAL_ORDER */

i don't think the template functions have any association with the partial specialization of function templates. am i wrong ?

How a function call is being treated by the compiler

Calling a function template in C++ goes through the Holy Trinity of Name Lookup (section 3.4 in the Standard), Template Argument Deduction (section 14.8.2) and Overload resolution (section 13.3).

Apart from reading these sections in the C++ Standard, you can read about it in the excellent book C++ Templates: The Complete Guide, or watch the first three Core C++ videos by Stephan T. Lavavej

A glimpse into the Standard

As you already found out yourself, the macro was originally in the SGI implementation of the STL, at a time when there was not C++ Standard yet and compiler support for function templates was very sketchy.

// * __STL_FUNCTION_TMPL_PARTIAL_ORDER: defined if the compiler supports // partial ordering of function templates. (a.k.a partial specialization // of function templates.)

To find out what partial ordering of function templates is used for, here's a quote (which will become much clearer if you read the book and watch the linked videos).

14.5.6.2 Partial ordering of function templates [temp.func.order]

1 If a function template is overloaded, the use of a function template specialization might be ambiguous because template argument deduction (14.8.2) may associate the function template specialization with more than one function template declaration. Partial ordering of overloaded function template declarations is used in the following contexts to select the function template to which a function template specialization refers:

— during overload resolution for a call to a function template specialization (13.3.3);

— when the address of a function template specialization is taken;

— when a placement operator delete that is a function template specialization is selected to match a placement operator new (3.7.4.2, 5.3.4);

— when a friend function declaration (14.5.4), an explicit instantiation (14.7.2) or an explicit specialization (14.7.3) refers to a function template specialization.

2 Partial ordering selects which of two function templates is more specialized than the other by transforming each template in turn (see next paragraph) and performing template argument deduction using the function type. The deduction process determines whether one of the templates is more specialized than the other. If so, the more specialized template is the one chosen by the partial ordering process.

can we declare a template function in a normal class with out a template class or is it should be always inside a template class ?

Yes you can , but make sure your definition and declaration of the template function is in the header files. If you want to know more why is this like that or more about templates in general i can recommend you this book Templates - Complete Guide

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 have code something like this

template <typename T> void fun (T value)
{
    .....
    value.print ();  //Here if T is a class I want to call print (), 
                     //otherwise use printf
    .....
}

Now, to print the value, if T is a class, I want to call the print function of the object, but if T is a basic datatype, I just want to use printf.

So, how do I find if the Template type is a basic data type or a class?

If you don't have C++11 support, an alternative.

template<typename T>
class isClassT {
private:
    typedef char One;
    typedef struct { char a[2]; } Two;
    template<typename C> static One test(int C::*);
    template<typename C> static Two test(…);
public:
    enum { Yes = sizeof(isClassT<T>::test<T>(0)) == 1 };
    enum { No = !Yes };
};

A simple template for finding out if type is class type. More in C++ Templates a Complete Guide.

if (isClassT<T>::Yes) {
    std::cout << " Type is class " << std::endl;
}

Is there a difference between a class template and template class. If so what is it?

Nowadays the two are used interchangeably because of the influence of C++. In the old days, pre-C++ templates, however, a template class was part of object-oriented design terminology. The idea behind a template class was that it formed the framework of execution with clearly defined, overridden "hotspots" (virtual methods in implementation) that subclasses would provide the functionality in. The effect was something like the following pseudocode:

class templateClass:
  public:
    virtual hotSpotA: nil
    virtual hotSpotB: nil
    method templateExecute:
      do some stuff
      hotSpotA
      do some other stuff
      hotSpotB
      do even more stuff

You would then use this template class by inheriting from it and implementing the hotSpots:

class templateClient from templateClass:
  public:
    override hotSpotA:
      client-specific stuff A
    override hotSpotB:
      client-specific stuff B

client = new templateClient
client.templateExecute

A lot of design meta-patterns relied upon this kind of structure (and, indeed, if you look at most OO design patterns you'll see this kind of structure in various forms used all the time).

Nowadays you'll not see this terminology used this way very much any more because of the pernicious influence of C++. I'm not sure what the current term for this meta-pattern structure is because I've pretty much ditched OOP entirely except when forced to use it.

There was a book that explained this (and other meta-patterns) in great detail should you wish to read it: Design Patterns for Object-Oriented Software Development

This question is also addressed specifically in the definitive book on C++ Templates ("C++ Templates: The Definitive Guide", by Vandvoorde and Josuttis), Section 7.1, p.87 (at least in my edition):

7.1 "Class Template" or "Template Class"?

[snip]

There is some confusion about how a class that is a template is called:

The term class template states that the class is a template. That is, it is a parameterized description of a family of classes.

The term template class on the other hand has been used

  • as a synonym for class template.

  • to refer to classes generated from templates.

  • to refer to classes with a name that is a template-id.

The difference between the second and third meaning is somewhat subtle and unimportant for the remainder of the text.

Because of this imprecision, we avoid the term template class in this book.

Similarly, we use function template and member function template, but avoid template function and template member function.

(Anyone, I mean anyone, working with C++ templates should have a copy of this book, by the way.)

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,
Ovanes

I can compile some code which fills a vector of raw pointers to a base class with pointers to a templated inherited class. But I've tried using the standard library and boost smart pointers instead of raw pointers, and the code doesn't compile. Can you explain why not?

This works:

vector<base*> vec
inherited<double>* elem = new inherited<double> >();
vec.push_back(elem);

This doesn't:

vector<auto_ptr<base> > vec
auto_ptr<inherited<double> >(new inherited<double> >());
vec.push_back(elem);

I don't really care whether or not what I'm trying to do is reasonable I'm just feeling out what's possible.

My full 60 LOC is here: https://gist.github.com/melvyniandrag/f432140c1aa216696bb6

Don't beat me up guys I've read a bit of C++ Templates: The Complete Guide (2002) and some posts here, but haven't been able to expediently connect the dots.

You can do this using std::shared_ptr and std::static_pointer_cast.

vector<shared_ptr<base> > vec;
shared_ptr<inherited<double> > elem(new inherited<double> >());
vec.push_back(static_pointer_cast<inherited<double>,base>(elem));

I'm reading the C++ Templates: The complete guide book and in chapter 4 (4.2 Nontype Function Template Parameters) is an example of a template function that can be used with STL containers to add a value to each element of a collection. Here is the complete program:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>


template<typename T, int VAL>
T addValue(T const& x)
{
    return x + VAL;
}

int main()
{
    std::vector<int> source;
    std::vector<int> dest;
    source.push_back(1);
    source.push_back(2);
    source.push_back(3);
    source.push_back(4);
    source.push_back(5);

    std::transform(source.begin(), source.end(), dest.begin(), (int(*)(int const&)) addValue<int, 5>);
    std::copy(dest.begin(), dest.end(), std::ostream_iterator<int>(std::cout, ", "));

    return 0;
}

I had to make that ugly cast because the book states that:

Note that there is a problem with this example: addValue<int,5> is a function template, and function templates are considered to name a set of overloaded functions (even if the set has only one member). However, according to the current standard, sets of overloaded functions cannot be used for template parameter deduction. Thus, you have to cast to the exact type of the function template argument:

std::transform (source.begin(), source.end(),  // start and end of source 
                dest.begin(),                  // start of destination 
                (int(*)(int const&)) addValue<int,5>);  // operation 

My problem is that I get an segmentation fault when running the program. I am building it using Clang on the Mac.
Is the cast incorrect or what else could the problem be ?

The cast is not your problem, you are outputting elements to an empty vector. Instead you could resize the space you will need:

dest.resize(source.size());

or better yet let transform figure that out:

std::transform(
    source.begin(), source.end()
  , std::back_inserter( dest ) // needs <iterator>
  , &addValue<int, 5> // cast should not be needed
);

although if you do know how much space it will take, resize-ing the vector will have better performance as it will avoid internal reallocation as items are added. Another alternative is to call reserve to avoid internal reallocation:

dest.reserve(source.size());
// dest is still empty

std::transform(
    source.begin(), source.end()
  , std::back_inserter( dest ) // needs <iterator>
  , &addValue<int, 5> // cast should not be needed
);

I am unable to understand the output of the following C++ snippet.

Should not objc.fn() call A's fn() since B's fn() is private and should not be visible in C. However, the answer is: the call to fn() is ambiguous. How?

#include<iostream>
using namespace std;

class A{
  public:
   void fn() { cout << "1"; }
};
class B{
   void fn() { cout << "2"; }
};
class C: public A, public B {};

int main(){
  C objc;
  objc.fn();
  return 0;
}

According to the book C++ Templates: The Complete Guide Appendix B.1,

At a very high level, a call to a named function can be processed in the following way:

  1. The name is looked up to form an initial overload set.

  2. If necessary, this set is tweaked in various ways (for example, template deduction occurs).

  3. Any candidate that doesn't match the call at all (even after considering implicit conversions and default arguments) is eliminated from the overload set. This results in a set of so-called viable function candidates.

  4. Overload resolution is performed to find a best candidate. If there is one, it is selected; otherwise, the call is ambiguous.

  5. The selected candidate is checked. For example, if it is an inaccessible private member, a diagnostic is issued.

As you can see, the access authority is checked at last, so the call to fn() is ambiguous will be reported first at step 4.

I have a vector with int elements and a vector with float elements. In that case most preffered type is float and in dot product I want to return a float type (if not specified).

The following code does just this, but something goes wrong with template packs.

Can I have a little bit of help?

#include <iostream>
#include <vector>
#include <array>
using namespace std;


template<typename Tp, typename T1> struct contains
{
    constexpr static bool value = std::is_same<Tp, T1>::value;
};
template<typename Tp, typename T1, typename ... Tn> struct contains
{
    constexpr static bool value = std::is_same<Tp, T1>::value || contains<Tp, Tn...>::value;
};

template<typename ... T> struct perfect
{
    typedef 
        typename std::conditional<contains<long double, T...>::value, long double,
        typename std::conditional<contains<double     , T...>::value, double,
        typename std::conditional<contains<float      , T...>::value, float,
        typename std::conditional<contains<long long  , T...>::value, long long,
        typename std::conditional<contains<unsigned long long, T...>::value, unsigned long long,
        typename std::conditional<contains<int        , T...>::value, int,
        typename std::conditional<contains<unsigned int, T...>::value, unsigned int,
        //.....
        void
        >>>>>>>::type type;
};


struct Vector1 : public std::vector<double> {};
struct Vector2 : public std::vector<int> {};
struct Vector3 : public std::vector<float> {};

template<typename C1, typename C2, typename T = perfect<typename C1::value_type, typename C2::value_type>::type>
T dot_product(const C1 &c1, const C2 &c2)
{
    return 0; // return c1 * c2
} 

int main()
{
    Vector1 a;
    Vector2 b;
    cout << dot_product(a, b) << endl;
    cout << dot_product<Vector1, Vector2, long double>(a, b) << endl;
}

You are missing two things here.

template<typename Tp, typename T1> struct contains
{
    constexpr static bool value = std::is_same<Tp, T1>::value;
};

is a specialization so it should be

template<typename Tp, typename T1> struct contains<T1,Tp>
                                               // ^^^^^^ 
{
    constexpr static bool value = std::is_same<Tp, T1>::value;
};

and it should be defined after the original template.


Next you are missing typename here.

template<typename C1, typename C2, typename T = typename perfect<typename C1::value_type, typename C2::value_type>::type>
                                             // ^^^^^^^ 

However I should mention that you are probably over complicating it here. I am not sure if all of this is necessary for deduction from two types. Maybe pre-processor macros can do this much better for you. I am assuming this is an exercise.



EDIT:
OK Here is a similar operation but different approach from C++ Templates a Complete Guide . Old but still enough for your options

#define MK_PROMOTION(T1,T2,Tr)             \
    template<> class Promotion<T1, T2> {   \
      public:                              \
        typedef Tr type;                   \
    };                                     \
                                           \
    template<> class Promotion<T2, T1> {   \
      public:                              \
        typedef Tr type;                   \
    };



template<typename T1, typename T2>
class Promotion {
public:
    typedef T1 type;    
};


template<typename T>
class Promotion<T,T> {
  public:
    typedef T type;
};

MK_PROMOTION(int, char, int)
MK_PROMOTION(double, float, double)
MK_PROMOTION(double, int, double)




typedef std::vector<double> Vector1;
typedef std::vector<int> Vector2;
typedef std::vector<float> Vector3;


template<typename C1, typename C2, typename T = typename Promotion< typename C1::value_type, typename C2::value_type >::type >
T dot_product(const C1 &c1, const C2 &c2)
{
    return 0; // return c1 * c2
} 

int main()
{
    Vector1 a;
    Vector2 b;
    cout << dot_product(a, b) << endl;
    cout << dot_product<Vector1, Vector2, long double>(a, b) << endl;
}

As an example in this book: http://www.amazon.com/C-Templates-The-Complete-Guide/dp/0201734842 they have this class:

template <typename T> 
class Stack { 
 private: 
 std::deque<T> elems; // elements
 public: 
 void push(T const&); // push element
 void pop(); // pop element
 T top() const; // return top element
 bool empty() const { // return whether the stack is empty
 return elems.empty(); 
 } 
 // assign stack of elements of type T2 
 template <typename T2> 
 Stack<T>& operator= (Stack<T2> const&); 
}; 

And here is the implementation of assign operator:

template <typename T> 
 template <typename T2> 
Stack<T>& Stack<T>::operator= (Stack<T2> const& op2) 
{ 
 if ((void*)this == (void*)&op2) { // assignment to itself?
 return *this; 
 } 
 Stack<T2> tmp(op2); // create a copy of the assigned stack
 elems.clear(); // remove existing elements
 while (!tmp.empty()) { // copy all elements
 elems.push_front(tmp.top()); 
 tmp.pop(); 
 } 
 return *this; 
} 

And here is some explanation on what that method does:

Inside the member function you may expect simply to access all necessary data for the assigned stack op2. However, this stack has a different type (if you instantiate a class template for two different types, you get two different types), so you are restricted to using the public interface. It follows that the only way to access the elements is by calling top(). However, each element has to become a top element, then. Thus, a copy of op2 must first be made, so that the elements are taken from that copy by calling pop().

I am getting confused with this part:

However, this stack has a different type (if you instantiate a class template for two different types, you get two different types), so you are restricted to using the public interface.

Does this say that i am allowed ONLY to use public interfases, or i am NOT allowed to use public intefaces? If it means that i am not allowed to use public interfases, than what is a top() member function? Isn't it a public method?

However, this stack has a different type (if you instantiate a class template for two different types, you get two different types), so you are restricted to using the public interface.

It means that you should use only public interface. In fact, if you want to implement the operator= function then you must use only public interface.

In case you don't use a public interface you won't be able to access the top() function and that is the only way you can assign the elements of the stack to the other stack.

Yes, top() is a public function.

Following code works fine:

template<typename T>
struct Wrap {};

template<template <class> class OUT, typename IN>
void Extract (OUT<IN> *obj)
{ /* only class 'IN' is used in some way */ }

int main ()
{
  Wrap<int> obj;
  Extract(&obj);
}

But, I am passing a pointer argument to extract the outer type and inner type.

Is there any better way by which I can invoke the method with explicit template instantiation ? Extract<Wrap<int> > ();

Edit:

I will detail my question a bit more. This explains, why the easy answer like Extract<Wrap, int>(); is not possible. I am writing a text parser, for C++ code. Wherever, parser finds,

x = (Type) y; 

it should convert into,

x = Extract<Type> (y);

Now, the Type can be

  1. any normal type like, int* or A**
  2. some templatized template like Wrap<A>

Now, Extract() works different for both the cases. I have to figure out using template that, whether it's Extract<int*> or Extract<Wrap<int> >.

==> In simpler language, the method can be called:

  1. Extract<int*>()
  2. Extract<Wrap<int> >()

I can figure out if it's called in 1st case, but how can I figure out if it's called in 2nd case ? (provided that, I want to know internal type also).

This works fine

template<typename T>
struct Wrap {};

template<template <class> class OUT, typename IN>
void Extract ()
{
    IN x; // IN => int
} 

int main ()
{
  Wrap<int> obj;
  Extract<Wrap, int>();
}

You certainly lack basic understanding of C++ templates. Read the book C++ Templates - The Complete Guide.

I have some code that compiles and runs on MSVC++ but will not compile on GCC. I have made a test snippet that follows. My goal was to move the static method from BFSMask to BFSMaskSized. Can someone explain what is going on with the errors (esp. the weird 'operator<' error)? Thank you.

In the case of both #defines are 0, then the code compiles on GCC.

#define DOESNT_COMPILE_WITH_GCC     0
#define FUNCTION_IN_PARENT          0

I get errors if I change either #define to 1. Here are the errors I see.

#define DOESNT_COMPILE_WITH_GCC     0
#define FUNCTION_IN_PARENT          1
Test.cpp: In static member function 'static typename Snapper::BFSMask<T>::T_Parent::T_SINT Snapper::BFSMask<T>::Create_NEZ(TCMP)':
Test.cpp(492): error: 'CreateMaskFromHighBitSized' was not declared in this scope

#define DOESNT_COMPILE_WITH_GCC     1
#define FUNCTION_IN_PARENT          0
Test.cpp: In static member function 'static typename Snapper::BFSMask<T>::T_Parent::T_SINT Snapper::BFSMask<T>::Create_NEZ(TCMP) [with TCMP = int, T = int]':
Test.cpp(500):   instantiated from 'TVAL Snapper::BFWrappedInc(TVAL, TVAL, TVAL) [with TVAL = int]'
Test.cpp(508):   instantiated from here
Test.cpp(490): error: invalid operands of types '<unresolved overloaded function type>' and 'unsigned int' to binary 'operator<'

#define DOESNT_COMPILE_WITH_GCC     1
#define FUNCTION_IN_PARENT          1
Test.cpp: In static member function 'static typename Snapper::BFSMask<T>::T_Parent::T_SINT Snapper::BFSMask<T>::Create_NEZ(TCMP) [with TCMP = int, T = int]':
Test.cpp(500):   instantiated from 'TVAL Snapper::BFWrappedInc(TVAL, TVAL, TVAL) [with TVAL = int]'
Test.cpp(508):   instantiated from here
Test.cpp(490): error: invalid operands of types '<unresolved overloaded function type>' and 'unsigned int' to binary 'operator<'

Here is the code

namespace Snapper
{
#define DOESNT_COMPILE_WITH_GCC     0
#define FUNCTION_IN_PARENT          0

    // MASK TYPES
    // NEZ  - Not Equal to Zero
    #define BFSMASK_NEZ(A)      ( ( A ) | ( 0 - A ) )
    #define BFSELECT_MASK(MASK,VTRUE,VFALSE)    ( ((MASK)&(VTRUE)) | ((~(MASK))&(VFALSE)) )
    template<typename TVAL> TVAL BFSelect_MASK(TVAL MASK,TVAL VTRUE,TVAL VFALSE)
    { return(BFSELECT_MASK(MASK,VTRUE,VFALSE)); }

    //-----------------------------------------------------------------------------
    // Branch Free Helpers

    template<int BYTESIZE> struct BFSMaskBase {};
    template<> struct BFSMaskBase<2>
    {
        typedef UINT16  T_UINT;
        typedef SINT16  T_SINT;
    };
    template<> struct BFSMaskBase<4>
    {
        typedef UINT32  T_UINT;
        typedef SINT32  T_SINT;
    };
    template<int BYTESIZE> struct BFSMaskSized : public BFSMaskBase<BYTESIZE>
    {
        static const int SizeBytes      = BYTESIZE;
        static const int SizeBits       = SizeBytes*8;
        static const int MaskShift      = SizeBits-1;
        typedef typename BFSMaskBase<BYTESIZE>::T_UINT      T_UINT;
        typedef typename BFSMaskBase<BYTESIZE>::T_SINT      T_SINT;

#if FUNCTION_IN_PARENT
        template<int N> static T_SINT CreateMaskFromHighBitSized(typename BFSMaskBase<N>::T_SINT inmask);
#endif
    };

    template<typename T> struct BFSMask : public BFSMaskSized<sizeof(T)>
    {
        //  BFSMask = -1 (all bits set)

        typedef BFSMask<T>                      T_This;
        // "Import" the Parent Class
        typedef BFSMaskSized<sizeof(T)>         T_Parent;
        typedef typename T_Parent::T_SINT       T_SINT;

#if FUNCTION_IN_PARENT
        typedef T_Parent    T_MaskGen;
#else
        typedef T_This      T_MaskGen;
        template<int N> static T_SINT CreateMaskFromHighBitSized(typename BFSMaskSized<N>::T_SINT inmask);
#endif

        template<typename TCMP> static T_SINT Create_NEZ(TCMP A)
        {
            //ReDefineType(const typename BFSMask<TCMP>::T_SINT,SA,A);
            //const typename BFSMask<TCMP>::T_SINT cmpmask = BFSMASK_NEZ(SA);
            const typename BFSMask<TCMP>::T_SINT cmpmask = BFSMASK_NEZ(A);
#if DOESNT_COMPILE_WITH_GCC
            return(T_MaskGen::CreateMaskFromHighBitSized<sizeof(TCMP)>(cmpmask));
#else
            return(CreateMaskFromHighBitSized<sizeof(TCMP)>(cmpmask));
#endif
        }
    };

    template<typename TVAL> TVAL BFWrappedInc(TVAL x,TVAL minval,TVAL maxval)
    {
        const TVAL diff = maxval-x;
        const TVAL mask = BFSMask<TVAL>::Create_NEZ(diff);
        const TVAL incx = x + 1;
        return(BFSelect_MASK(mask,incx,minval));
    }

    SINT32 currentsnap = 0;
    SINT32 SetSnapshot()
    {
        currentsnap=BFWrappedInc<SINT32>(currentsnap,0,20);
        return(currentsnap);
    }
}

Expanding on the answer given by sth: this is explained in C++ Templates: The Complete Guide like this, in section 9.3.3 Dependent Names of Templates:

In general, a C++ compiler is required to treat a < following the name of a template as the beginning of a template argument list; otherwise it is a "less than" operator. As is the case with type names, a compiler has to assume that a dependent name does not refer to a template unless the programmer provides extra information using the keyword template[.]

I'm reading C++ Templates: The Complete Guide, and in "13.7 Partial Specialization of Function Templates" author said:

To overload function templates, their function parameters must differ in some material way. Consider a function template R convert(T const&) where R and T are template parameters. We may very well want to specialize this template for R = void, but this cannot be done using overloading.

It could be done using function template overloading, right? Such as:

#include <iostream>

template <typename T, typename R>
R convert(T const&) { std:: cout << "R convert(T const&)\n"; }
template <typename T>
void convert(T const&) { std:: cout << "void convert(T const&)\n"; }

int main()
{
    convert(0);
}

DEMO here, result is:

void convert(T const&)

What does author really mean?

Consider a class template partial specialization:

template<class U, class V> class T { };

template<class V> class T<void, V> { };

When you write T<void, int>, the partial specialization will be used.

Now consider a function template:

template <typename R, typename T>
R convert(T const&) { return /* something */; } 

Note that the order of R and T are swapped in the template parameter list above. This is probably how such a template would be written - you write convert<R>(something), explicitly specifying the destination type while letting the source type be deduced by the compiler.

Now suppose you want convert<void>(something) to do something different. You can't do it with an overload:

template <typename T>
void convert(T const&) { } 

If you write convert(something) - which would previously be ill-formed, it will go to your new overload, because the compiler can't deduce R for the first template. But if you write convert<void>(something) or even convert<void, T>(something), it would still go to the original template. To make it worse, something like convert<int>(1) is now ill-formed because it's ambiguous.

In other words, you can't make convert<void, T>(something) use a different implementation than convert<int, T>(something), whereas you can do this with class template partial specializations.

I'm trying to convert a class from an "ordinary" class to a template class, and I don't understand the correct syntax. Below is a (greatly simplified) example of what I'm starting with. This is Visual Studio 2010, C++, targeted to x64 architecture, Windows 7.

The goal is to rewrite class T as a template to handle either TEntry or a new class, OtherTEntry, similar to TEntry in concept, with the same member functions, but having different data members.

I'd appreciate advice on how best to do this. I'd like to keep the header and implementation files separate, if possible. I am particularly stuck on the references to a local variable T *, and how to use sizeof() properly.

In file T.h:

class T
{
    T(void);
    T(G *pGIn, const unsigned long s, char nIn);
    ~T(void);

    // Member functions
    public:
    bool Expand(const unsigned long newS);
    void Empty(void);

    private:
    G *pG;
    char n;
    unsigned long s;
    int f;
    TEntry *p;
};

In file TEntry.h:

class TEntry
{
    // Constructors
    public:
    TEntry();
    TEntry(int l);

    // Member functions
    public:
    void Relocate(int delta);

private:

    // Data members
    int k;
    TEntry *p;
};

In file T.cpp:

T::T()
{
    p=NULL; s=0; pG=NULL;
    Empty();
    return;
}

T::T(G *pGIn, const unsigned long m, char nIn)
{
    pG=pG; n=nIn;
    return;
}

T::~T(void)
{
    if(p!=NULL)
        delete[] p;
    return;
}

bool T::Expand(const unsigned long newS)
{
    T *pBefore=p;
    p=(T *)_realloc_dbg(p, newS*sizeof(T), _NORMAL_BLOCK,__FILE__,__LINE__);
    s=newS;
    return p!=NULL;
}

void T::Empty()
{
    f=0;
    return;
}

In file TEntry.cpp:

T::T()
{
}

T::T(int i)
{
    k=i;
}

void T::Relocate(int delta)
{
    k+=delta;
    return;
}

In general, it is preferred to keep template code in .h files. If absolutely necessary, it is possible to put the implementation in the .cpp file, please consult C++ Templates: The Complete Guide by David Vandevoorde and Nicolai M. Josuttis, Chaprer 6, for details.

You can go like this (cut down less important details):

template <class T>
class YourClass
{
    YourClass()
       : p(NULL), s(0), pG(NULL)
    {
       Empty();
    }

    YourClass(G *pGIn, const unsigned long s, char nIn)
    {
       // ... implementation here
    }
    ~YourClass()
    {
        if(p!=NULL)
           delete p;
    }


public:
    bool Expand(const unsigned long newS)
    {
        T *pBefore=p;
        p=(T *)_realloc_dbg(p, newS*sizeof(T), _NORMAL_BLOCK,__FILE__,__LINE__);
        s=newS;
        return p!=NULL;
    }


private:
    G *pG;
    char n;
    unsigned long s;
    int f;
    T* p;
};

Few notes:

  • Naming your class template T is really a bad idea because it is a common practice to use T for template parameter names.
  • Regarding the sizeof, in your code example it is not applied to the template, but to a usual class, anyway, there shouldn't be any problem using sizeof on a class, class template or a template parameter.
Linking... 
Directory.obj : error LNK2019: unresolved external symbol "public: void __thiscall indexList<class entry,100>::read(class std::basic_istream<char,struct std::char_traits<char> > &)" (?read@?$indexList@Ventry@@$0GE@@@QAEXAAV?$basic_istream@DU?$char_traits@D@std@@@std@@@Z) referenced in function _main

Getting this error and others associated with indexList implementation. I have included all the right files, not sure what this means?

indexList.h
indexList.cpp

Also, using VS .NET 2003 - They are under the "Source Files" and "Header Files" However, I tested with deleting the indexLish.h and the error doesn't change?

Since you are using templates, the best way is to include the definition in .H file.

I read something from this book . And here is something it may help you too.

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:

Books

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 .

while going through some of the mili source code I came across a struct declared like this:

template <class T, class Pre, class Pos>
struct PrePosCaller<T*, Pre, Pos>

(from here)

The part I'm unfamiliar with is <T*, Pre, Pos>. I understand what the code does and its purpose in this context but I would like to know where it is documented so I can learn/understand it a bit more.

I would like to know where it is documented

If you are looking for an introduction as well as background to the subject, get yourself a copy of C++ Templates: The Complete Guide.
While the definitive documentation is the C++ standard itself, its no fun to approach it without a well written overview.

For the coming holiday season on the beach I would like to buy this book C++ Templates: The Complete Guide.

I am NOT asking if this book can be recommended, because then this question will be immediately closed as too broad or primarily opinion-based.

My question:

Were there - if any - significant changes in the C++ template standard since 2002 which would mean the book may be expired [because these changes cannot be handled in this book] or didn't really change that much and therefore the book is still up-to-date.

2002 is ancient history, predating both C++03 and especially C++11 and C++14. Many things have changed - also in relation to templates.

Just a few examples:

Alias template : http://en.cppreference.com/w/cpp/language/type_alias

Extern template : https://en.wikipedia.org/wiki/C%2B%2B11#Extern_template

Variadic templates : http://www.stroustrup.com/C++11FAQ.html#variadic-templates

decltype : http://en.cppreference.com/w/cpp/language/decltype

declval : http://en.cppreference.com/w/cpp/utility/declval

And much, much more..