Modern C++ Design

Andrei Alexandrescu

Mentioned 78

This title documents a convergence of programming techniques - generic programming, template metaprogramming, object-oriented programming and design patterns. It describes the C++ techniques used in generic programming and implements a number of industrial strength components.

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.

I've seen some examples of C++ using template template parameters (that is templates which take templates as parameters) to do policy-based class design. What other uses does this technique have?

Here is a simple example taken from 'Modern C++ Design - Generic Programming and Design Patterns Applied' by Andrei Alexandrescu:

He uses a classes with template template parameters in order to implement the policy pattern:

// Library code
template <template <class> class CreationPolicy>
class WidgetManager : public CreationPolicy<Widget>
{
   ...
};

He explains: Typically, the host class already knows, or can easily deduce, the template argument of the policy class. In the example above, WidgetManager always manages objects of type Widget, so requiring the user to specify Widget again in the instantiation of CreationPolicy is redundant and potentially dangerous.In this case, library code can use template template parameters for specifying policies.

The effect is that the client code can use 'WidgetManager' in a more elegant way:

typedef WidgetManager<MyCreationPolicy> MyWidgetMgr;

Instead of the more cumbersome, and error prone way that a definition lacking template template arguments would have required:

typedef WidgetManager< MyCreationPolicy<Widget> > MyWidgetMgr;

When I first learned C++ 6-7 years ago, what I learned was basically "C with Classes". std::vector was definitely an advanced topic, something you could learn about if you really wanted to. And there was certainly no one telling me that destructors could be harnessed to help manage memory. Today, everywhere I look I see RAII and SFINAE and STL and Boost and, well, Modern C++. Even people who are just getting started with the language seem to be taught these concepts almost from day 1.

My question is, is this simply because I'm only seeing the "best", that is, the questions here on SO, and on other programming sites that tend to attract beginners (gamedev.net), or is this actually representative of the C++ community as a whole?

Is modern C++ really becoming the default? Rather than being some fancy thing the experts write about, is it becoming "the way C++ just is"? Or am I just unable to see the thousands of people who still learn "C with classes" and write their own dynamic arrays instead of using std::vector, and do memory management by manually calling new/delete from their top-level code?

As much as I want to believe it, it seems incredible if the C++ community as a whole has evolved so much in basically a few years. What are your experiences and impressions?

(disclaimer: Someone not familiar with C++ might misinterpret the title as asking whether C++ is gaining popularity versus other languages. That's not my question. "Modern C++" is a common name for a dialect or programming style within C++, named after the book "Modern C++ Design: Generic Programming and Design Patterns Applied", and I'm solely interested in this versus "old C++". So no need to tell me that C++'s time is past, and we should all use Python ;))

Here's how I think things have evolved.

The first generation of C++ programmers were C programmers, who were in fact using C++ as C with classes. Plus, the STL wasn't in place yet, so that's what C++ essentially was.

When the STL came out, that advanced things, but most of the people writing books, putting together curricula, and teaching classes had learned C first, then that extra C++ stuff, so the second generation learned from that perspective. As another answer noted, if you're comfortable writing regular for loops, changing to use for_each doesn't buy you much except the warm fuzzy feeling that you're doing things the "modern" way.

Now, we have instructors and book writers who have been using the whole of C++, and getting their instructions from that perspective, such as Koenig & Moo's Accelerated C++ and Stroustrup's new textbook. So we don't learn char* then std::strings.

It's an interesting lesson in how long it takes for "legacy" methods to be replaced, especially when they have a track record of effectiveness.

In a recent interview, I was asked a really strange question. The interviewer asked me how can I compute 1+2+3+...+1000 just using compiler features. This means that I am not allowed to write a program and execute it, but I should just write a program that could drive the compiler to compute this sum while compilation and print the result when compilation completes. As a hint, he told me that I may use generics and pre-processor features of the compiler. It is possible to use C++, C# or Java compiler. Any ideas???

This question is not related to computing the sum without any loops asked here. In addition, It should be noted that the sum SHOULD be calculated during compilation. Printing just the result using C++ compiler directives is not acceptable.

Edit:

Reading more about the posted answers, I found that solving problems during compilation using C++ templates is called metaprogramming. This is a technique that was discovered accidentally by Dr. Erwin Unruh, during the process of standardizing the C++ language. You may read more about this topic on wiki page of meta-programming. It seems that it is possible to write the program in Java using java annotations. You may take a look at maress's answer below.

Edit 2:

A nice book about meta-programming in C++ is this one. Worth to take a look if interested.

Edit 3

A useful C++ meta-programming library is Boost's MPL this link.

Updated Now with improved recursion depth! Works on MSVC10 and GCC without increased depth. :)


Simple compile-time recursion + addition:

template<unsigned Cur, unsigned Goal>
struct adder{
  static unsigned const sub_goal = (Cur + Goal) / 2;
  static unsigned const tmp = adder<Cur, sub_goal>::value;
  static unsigned const value = tmp + adder<sub_goal+1, Goal>::value;
};

template<unsigned Goal>
struct adder<Goal, Goal>{
  static unsigned const value = Goal;
};

Testcode:

template<unsigned Start>
struct sum_from{
  template<unsigned Goal>
  struct to{
    template<unsigned N>
    struct equals;

    typedef equals<adder<Start, Goal>::value> result;
  };
};

int main(){
  sum_from<1>::to<1000>::result();
}

Output for GCC:

error: declaration of ‘struct sum_from<1u>::to<1000u>::equals<500500u>’

Live example on Ideone.

Output for MSVC10:

error C2514: 'sum_from<Start>::to<Goal>::equals<Result>' : class has no constructors
      with
      [
          Start=1,
          Goal=1000,
          Result=500500
      ]

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

Static metaprogramming (aka "template metaprogramming") is a great C++ technique that allows the execution of programs at compile-time. A light bulb went off in my head as soon as I read this canonical metaprogramming example:

#include <iostream>
using namespace std;

template< int n >
struct factorial { enum { ret = factorial< n - 1 >::ret * n }; };

template<>
struct factorial< 0 > { enum { ret = 1 }; };

int main() {
    cout << "7! = " << factorial< 7 >::ret << endl; // 5040
    return 0;
}

If one wants to learn more about C++ static metaprogramming, what are the best sources (books, websites, on-line courseware, whatever)?

Modern C++ Design, a brilliant book and design pattern framework by Alexandrescu. Word of warning, after reading this book I stopped doing C++ and thought "What the heck, I can just pick a better language and get it for free".

Modern C++ is one of the best introductions I've read. It covers actual useful examples of template metaprogramming. Also take a look at the companion library Loki.

I'm told that the template system in C++ is Turing-complete at compile time. This is mentioned in this post and also on wikipedia.

Can you provide a nontrivial example of a computation that exploits this property?

Is this fact useful in practice?

The Book Modern C++ Design - Generic Programming and Design Pattern by Andrei Alexandrescu is the best place to get hands on experience with useful and powerful generic programing patterns.

For new and completely revised tricks and dark corners of STL go here: Hidden Features and Dark Corners of STL

I've been using more "modern" c++ constructs for a while, but kind of superficially and not everywhere. I'm looking for open source projects to study that are good examples of Modern C++ and STL usage.

Things like what is suggested in Meyer's "Effective STL", such as trying to avoid for loops and replace them with more functional constructs, using boost::bind and boost::function, etc. These still feel a little unnatural to me, and when I have to get something done fast and working, I tend to drop back to libc and string.h (you can have my strtok when you pry it from my cold, dead, hands).

However, I've also had the positive experience of finding what would be a drastic change simplified because I've used these constructs, or being able to implement something with just a few lines of code because I had the right operators and functors lying around. In addition, I've recently been paying more attention to concurrency, and so this is becoming even more important to me.

Can you recommend some examples of well-written open source projects that make heavy use of the STL and other modern c++ techniques that I could study? I'm particularly interested in application code, browsing the boost sources has been helpful but it's by necessity very general because it's library code.

I'm interested in medium sized to larger projects, at least a few tens of thousands of lines. It's pretty easy to find examples that are a few hundred lines long but that's not too helpful.

Thank you.

Meyers is ok, however, if you really want to push yourself, you have to read

Andrei Alexandrescu - Modern C++ Design: Generic Programming and Design Patterns Applied

It will blow your mind. What you learn in the book describes the Loki library.

One of my favourites is the int to type conversions:

template <int v>
struct Int2Type
{
    enum { value = v };
};

I've used it in the past for my C++ XML serilisation library for pre-allocating vector<>'s before loading them with data:

// We want to call reserve on STL containers that provide that function,
// namely std::vector.
// However, we would get a compiler error if we tried to call reserve on
// a STL container that
// did not provide this function. This is the solution.
template <bool b, class T>
class CReserve
{
public:
    static void reserve(T &lst, const int &n)
    { reserve(lst, n, Loki::Int2Type<b>()); }

private:
    static void reserve(T &lst, const int &n, Loki::Int2Type<true>)
    { lst.reserve(n); }

    static void reserve(T &lst, const int &n, Loki::Int2Type<false>)
    { (void)lst; (void)n; }
};

Notice the private specialisations above. Well if you look closely, one calls reserve(), the other doesn't. This is a template specialisation using a bool as a type.

which in tern is used by:

template <bool bCallReserve, class T>
bool STLSerializeClassType(MSXML::IXMLDOMNodePtr pCurNode, T &lst, 
                           CXmlArchive &archive, const char *name)
{
    if(archive.IsStoring())
    {
        ...
    } else {
        lst.clear();

        T::size_type nCount(0);
        XML_ELEMENT(nCount);

        CReserve<bCallReserve, T>::reserve(lst, nCount);

        while(nCount--)
        {
            T::value_type temp;
            temp.SerializeXml(archive, pCurNode);
            lst.push_back(temp);
        }
    }
}

To make things simple in users C++ code, I added a lot of helper definitions

#define SERIALIZE_XML_STL_CLASS(list_name, bCallReserve) \
(HS::STLSerializeClassType<(bCallReserve)>
    (pCurNode, (list_name), archive, (#list_name))
)

so in your code you'd use something like:

std::list<CFred> fredList;
SERIALIZE_XML_STL_CLASS(fredList, false);

or for vectors:

vector<CFred> fredList;
SERIALIZE_XML_STL_CLASS(fredList, true);

Anyway, I'll stop wittering on... Thats just putting the simple Int2Type<> template to good use. There's loads of clever stuff like getting the compiler to compute a ton of stuff beforehand by clever use of enums. Truly awsome book.

Everyone has been telling me to learn C++. Without bashing languages right and left, can someone please state some relevant reasons as to why I should learn C++ today?

Note that in no way am I saying anything harsh about C++. I just want to know why I should master it as a programmer instead of the other powerful languages out there.

For any reasonably experienced software developer, learning a new statically typed object-oriented language should be a piece of cake. The main difficulty in learning a new language is learning the main API of the programming environment that you're in. For C++ that is really easy, the STL is pretty small, and as far as I know C++ doesn't really involve any other standard libraries.

Some of the most important reasons to learn C++ are:

  • Understanding memory management and pointer usage.
  • Inventing your own class hierarchy instead of relying on pre-packaged libraries from your language vendor.
  • Learning how to use templates and generic programming principles.

I think that last one is particularly important. No other language (at least the languages that I've used) does generic programming quite like C++. Alexandrescu is definitely a worthwhile book to pick up if you want to really understand the power of C++.

I discovered template metaprogramming more than 5 years ago and got a huge kick out of reading Modern C++ Design but I never found an opertunity to use it in real life.

Have you ever used this technique in real code?

Contributors to Boost need not apply ;o)

I once used template metaprogramming in C++ to implement a technique called "symbolic perturbation" for dealing with degenerate input in geometric algorithms. By representing arithmetic expressions as nested templates (i.e. basically by writing out the parse trees by hand) I was able to hand off all the expression analysis to the template processor.

Doing this kind of thing with templates is more efficient than, say, writing expression trees using objects and doing the analysis at runtime. It's faster because the modified (perturbed) expression tree is then available to the optimizer at the same level as the rest of your code, so you get the full benefits of optimization, both within your expressions but also (where possible) between your expressions and the surrounding code.

Of course you could accomplish the same thing by implementing a small DSL (domain specific language) for your expressions and the pasting the translated C++ code into your regular program. That would get you all the same optimization benefits and also be more legible -- but the tradeoff is that you have to maintain a parser.

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.

Tim Sweeney of Epic MegaGames is the lead developer for Unreal and a programming language geek. Many years ago posted the following screen shot to VoodooExtreme:

Tim Sweeney's screenshot

As a C++ programmer and Sweeney fan, I was captivated by this. It shows generic C++ code that implements some kind of scripting language where that language itself seems to be generic in the sense that it can define its own grammar.

Mr. Sweeney never explained himself. :-)

It's rare to see this level of template programming, but you do see it from time to time when people want to push the compiler to generate great code or because they want to create generic code (for example, Modern C++ Design).

Tim seems to be using it to create a grammar in Parser.cpp - you can see what look like prioritized binary operators. If that is the case, then why does Test.ae look like it's also defining a grammar?

Obviously this is a puzzle that needs to be solved. Victory goes to the answer with a working version of this code, or the most plausible explanation, or to Tim Sweeney himself if he posts an answer. :-)

So to clarify my question... each pattern in infamous GoF book - Design Patterns Elements of Reusable Object-Oriented Software - has its code samples in C++.

Are those up to date? Or does nowadays code in C++ look very different?

I'm asking that, because when I posted my code with my last question, lots of C++ devs told me that I should get rid of pointers, pointers that are widely used there...

They are a little out-dated, yes. But part of the point of those books is that these patterns are useful in several different languages and with several different styles. So while the code is a little old in the tooth, the ideas behind it aren't, and those ideas are what's important in those books.

I would like to see some pattern implementations that took advantage of meta-programming techniques. I strongly suspect some patterns, such as Bridge, Adapter and possibly Facade are much less tedious to implement using meta-programming. From the other answer, and reading the description, it looks like Modern C++ Design: Generic Programming and Design Patterns Applied might be a good book for this sort of thing. I can't personally vouch for it though.

Other than the possible use of generic programming and template techniques, the main differences are that bare pointers are a rare thing in C++ nowadays. There are effective smart pointer types that should usually be used instead because they handle a lot of the resource management issues for you. Frankly, unless you know really well what you are doing, I would not recommend attempting a generic programming based design anyway.

Here are some examples of which sorts of smart pointers to use in various contexts. These examples assume that you have a C++ that includes the TR1 (Technical Report 1) extensions:

When you have a pointer to something that is wholly owned by the object pointing to it, use ::std::auto_ptr (or ::std::unique_ptr in C++1x). Keep in mind that ::std::auto_ptr cannot be stored in STL containers, but ::std::unique_ptr does not have this problem. Examples might be the Component pattern (as long as no two sub-components were shared), the Facade pattern, and the Adapter pattern. Also, the Factory pattern should likely be producing ::std::auto_ptrs (or ::std::unique_ptrs in C++1x) unless there is a really good reason to be producing ::std::shared_ptrs.

When you have a pointer to something that has shared ownership, used ::std::tr1::shared_ptr. For example, the Flyweight pattern. Also, in some cases, the Component pattern may have this property as well. It may also be useful in Bridge pattern.

When you have a pointer to something that to something that you do not logically own, then a ::std::tr1::weak_ptr is the way to go. Keep in mind that if you use ::std::tr1::weak_ptr you should also use ::std::tr1::shared_ptr for all the objects that do logically own (or share ownership) of the pointed to item. An example for this is the Observer pattern.

Authors has used the code as examples, not that they've written production code. Production code are more robust and checks for errors and exceptions. Such books usually don't show these, neither do they contain try-catch block or other business-logic.

The book is intended for ideas, concepts, as to how to design your program to solve commonly occurring software problems, rather than what syntax or code to use. Also, wherever the authors has used raw pointers, you can replace them with smart pointers and the likes (if possible), to make it more robust.

However, dynamic polymorphism can be acheived only through pointers or references, so they're something that're still valid, and used even in production code.

Besides, its also true that in the last decade the way C++ code is written has changed a lot. So you can incorporate these new techniques with the old idea/patterns presented in the GOF's book. For example, Andrei Alexandrescu has used templates to implement many patterns (old patterns) in his book:

Modern C++ Design: Generic Programming and Design Patterns Applied

C++11 provides standard <type_traits>.

Which of them are impossible to implement without compiler hooks?

  • Note 1: by compiler hook I mean any non-standard language feature such as __is_builtin....
  • Note 2: a lot of them can be implemented without hooks (see chapter 2 of C++ Template Metaprogramming and/or chapter 2 of Modern C++ Design).
  • Note 3: spraff answer in this previous question cites N2984 where some type traits contain the following note: is believed to require compiler support (thanks sehe).

Per lastest boost documentation which is also a bit old but I think it's valid still

Support for Compiler Intrinsics

There are some traits that can not be implemented within the current C++ language: to make these traits "just work" with user defined types, some kind of additional help from the compiler is required. Currently (April 2008) Visual C++ 8 and 9, GNU GCC 4.3 and MWCW 9 provide at least some of the the necessary intrinsics, and other compilers will no doubt follow in due course.

The Following traits classes always need compiler support to do the right thing for all types (but all have safe fallback positions if this support is unavailable):

is_union
is_pod
has_trivial_constructor
has_trivial_copy
has_trivial_move_constructor
has_trivial_assign
has_trivial_move_assign
has_trivial_destructor
has_nothrow_constructor
has_nothrow_copy
has_nothrow_assign
has_virtual_destructor

The following traits classes can't be portably implemented in the C++ language, although in practice, the implementations do in fact do the right thing on all the compilers we know about:

is_empty
is_polymorphic

The following traits classes are dependent on one or more of the above:

is_class 

IMHO to me OOPS, design patterns make sense and i have been able to apply them practically.

But when it comes to "generic programming /meta programming" of the Modern C++ kind, i am left confused.

-- Is it a new programming/design paradigm ?

-- Is it just limited to "library development"? If not, What design/coding situations call for using meta programming/generic programming.

-- Does using templates mean i am doing generic programming?

I have googled a lot on this topic but do not grasp the BIG PICTURE fully. Also see this post.


After reading dicussions here under, up till now, I am sure ( might still not be correct):

a) Generic programming and meta programming are two different concepts.

For advanced templates and techniques, I recommend: Modern C++ Design, by Andrei Alexandrescu

C++ is a rigid language, with practically no runtime introspection capabilities. A lot of the troubles you'll encounter can be dealt with templates. Also, the templating language is turing-complete, making it possible to generate complex data-structures and pre-calculate values at compile-time, among other things. For many scenarios, it may be more trouble than it's worth it though.

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:

Can anyone recommend any good resources for learning C++ Templates?

Many thanks.

I've found cplusplus.com to be helpful on numerous occasions. Looks like they've got a pretty good intro to templates.

If its an actual book you're looking for, Effective C++ is a classic with a great section on templates.

Bruce Eckel's Thinking in C++ is how I learned about templates. The first volume has an introductory chapter and the second volume has an in-depth chapter on templates.

There's Bjarne Stroustrop's The C++ Programming Language which has a good chapter on them. And The C++ Standard Library: A Tutorial and Reference which is about the standard library, but would definitely help you get a better understanding of how templates could be used in the real world. .

This is a more advanced, but very useful, book on templates and template use.

Modern C++ Design

This post is in continuation of this one.

I am trying to understand if I am the only one who misses and needs the ability of a .NET generic type to inherit one of its generic parameter types.

The challenge is to collect compelling reasons in favour of this feature or, alternatively, get to know that there are none.

I give my reason to have it as an answer to this question - see below.

I am asking folks out there to add theirs as answers to this post.

If you disagree that the feature is useful or have no good reasons in favour - please refrain from posting anything here, though you can do so in the original post that has started it all - here.

P.S.

Some C++ patterns are irrelevant in .NET. For instance, in his excellent book Modern C++ Design Andrei Alexandrescu describes how to create a list of types evaluated at the compile time. Naturally, this pattern is irrelevant for .NET, where if I need a list of types I just create List<Type> and populate it with types. So, let us try to come up with reasons pertinent to the .NET framework and not just blindly translating C++ coding techniques to C#.

P.P.S.

Of course, this discussion is strictly academic. Even if a hundred compelling reasons for the feature in question is surfaced it is not going to be implemented, ever.

I have been learning C++ for three months now and in that time created a number of applications for my company. I consider myself fairly comfortable with C++ / MFC and STL, however I don't just want to be an OK programmer, I want to be a good programmer. I have a few books on best practices but I was wondering if anyone could suggest reading materials that helped them and any disciplines which should be encouraged?

Thanks!

You can check out the Boost library and a number of the books written about it. While this may not have been what you had in mind, IMO, the Boost libraries are examples of well-designed modern C++ libraries that use the features of the language in pretty much the way they should be used to create among the most effective solutions for their problem domain. Granted of course, there are bizarre libraries like preprocessor and MPL which make you wonder if you'll ever have any use for them, but they're all round quite good. From my own experience, exploring the library and its literature has given me insight into how C++ can be used effectively.

Boost Beyond the C++ Standard Library: An Introduction to Boost

For C++, Scott Meyers books are very good, and will help take you to the next level.

If you don't already have it C++ by Bjarne Stroustrup, 3rd Edition

3 months into c++ and you're already comfortable with it? Sheesh, I've been learning c# for over a year and have taken numerous Microsoft courses and I'm nowhere near comfortable with it.

That being said, you'll hear Code Complete tossed about as a very good book. I'm in the process of reading it now.

I lot of folks can suggest more modern, up-to-date books. But I still recommend The Annotated C++ Reference Manual by Margaret A. Ellis & Bjarne Stroustrup.

The ARM was published back in '90. It's become somewhat outdated with respect to templates. STL is (obviously) absent. (Though the website at sgi.com does a good job of covering STL!)

However, the ARM is dirt cheap (used). (Shipping will exceed the cost of the book.) Its signal-to-noise ratio remains off the scale. It's very good at digging into C++'s dirty areas, explaining what was done & why.

I still use it as a reference. I rank it up there with K&R.

Good blogs: Guru of the Week, and all the books by Herb Sutter. Those will give you quite a lot to chew already.

Modern C++ Design by Alexandrescu if you want to get a good feel for what you don't yet know, and probably don't want to know.

Code Kata's for practice!

As I see, nobody mentioned Bruce Eckel brilliant books "Thinking in C++". IMHO, it`s one of the best books to start your C++ development from. From my point of view, first volume is more helpful that the second, but both of them worth reading.
http://www.amazon.com/Thinking-C-Introduction-Standard-One/dp/0139798099/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1227890306&sr=8-1

I'm in high school and taking a class where basically we design our own course and choose what we learn. I've chosen to learn about C++ and game programming.

I'd like to learn as much about using C++ with OpenGL or DirectX or some other API as I can.

After I finish learning C++ where should I go? Can you recommend a book on game programming?

I too have once thought I knew most of C++... Then I read "Effective C++","Effective STL" , "C++ Gotchas" and "Modern C++ Design", and I realized just how wrong I was.

If you are looking to continue with gaming, C++ is a darn good place to start. You could also check out C# as it is used by Microsoft in XNA (XBox), Second Life, and by Unity on smart phones.

While I would not disagree with anybody about the math and reading you need to do, I think it is better to just roll up your sleeves and program. Read other people's code and then read so that you can understand why they are doing what they are doing.

If you think you know C++ well, the next step is to learn how to use it to make better software. For that, I would start with reading Effective C++.

If you really have a handle on C++ then perhaps this StackOverflow thread will answer your question about game books.

Personally, even if your goal is game programming, I would branch out from that to get a solid grounding as a developer.

Perhaps you should do a little web programming to get a feel for what that is all about. Maybe something like Ruby on Rails.

Alternatively, you could try to write a simple compiler or even an operating system to get a feel for what goes on under the hood and to learn that these too are just programs written by mortals.

Instead of writing your own, you could also get involved in an Open Source project. If I had the time, I would be all over spending time reading the code of Haiku and finding somewhere to contribute. Here is a list of open source game projects that you could consider joining as well.

Your chances of getting a decent job probably go up quite a bit if you know Java or .NET so those are also options. If you decide on .NET, I recommend checking out Mono.

I started programming in C++. It was my first language, but I have not used it in many years.

What are the new developments in the C++ world? What are the BIG things - technologies, books, frameworks, libraries, etc?

Over the last 7-8 years what are the biggest influences on C++ programming?

Perhaps we could do one influence per post, and that way we can vote on them.

"Modern C++", STL, template metaprogramming and Generic programming.

(And yes, they're one single answer, because they're pretty closely intertwined and together represent a complete paradigm shift in C++ development. While some of them are older than 8-9 years, it's pretty much in the last years that they've really gained traction and really left "C with classes" in the dust.

I've used function and class templates in implementation of my libraries. So far I've just instantiated a template in the library unit-tests (CppUnit), and then proceeded to test it almost like any other normal class or function.

Recently I've been planning to add some templates also to the library APIs. Good interface is of course the most important thing, template or not. With well designed and implemented templates you can, if not totally prevent, at least make it more difficult for the user to shoot himself in the foot. Any way I feel that unit-testing public templates need to be a bit more rigorous, compared to purely internal templates.

So, how have you unit-tested your C++ templates? Have you come up with any elegant solutions, especially for templates in public library APIs?

I have an additional suggestion. In addition to unit-testing each template, examine techniques that will help constrain the potentially vast universe of template arguments that your library users might try to pass to your templates.

For example: say that you only test your templates using the type arguments "string" and "char". You do not have proof that other type arguments will be problematic for this particular template, but for one reason or another you "suspect" that other untested type args will be problematic.

In a case such as the above example, it doesn't necessarily imply that you should exhaustively test other type args. Instead, you have a case that might imply you should employ some compile-time template metaprogramming techniques to ensure that your template is never used with any other arguments but "string" and "char".

One resource:

Modern C++ Design -- by Andrei Alexandrescu

Very early on in this book, the author shows examples such as:

  • how to make a template that will self-enforce that its first type arg be of a smaller type than its second type arg

  • how to detect convertibility and inheritance at compile time

"Modern C++ Design" (despite its rather broad/vague title) is a fairly advanced exploration of template programming techniques.

I was going through the Hilo tutorial series Developing C++ Applications for Windows 7; seemed pretty interesting.

What modern books that go into details of developing C++ based applications for Windows 7? It should show how to take advantage of Windows 7 features and based on "modern" C++ (templates, Unicode, etc.). Not looking for old school Petzold or MFC type books (sorry). Also should feature native code development (i.e. no Qt-/wx-type 3rd party libraries). The 3rd party libraries seems to be at least a generation behind and don't seem to leverage the latests features (ex. Ribbon, Animation etc.).

I don't know if it's still 'modern', but Modern C++ Design is a great resource on templates and generic algorithms.

I'd recommend that you ensure you're familiar with the theory in winprog.org/tutorial, then Ivor Horton's book (below), and then finally check out the WTL library.

The examples on the ribbon code in the Hilo articles use the windows API, which relies on COM objects to create the ribbon. ATL constructs like the CComPtr manage the lifetime of the ribbon objects and interfaces.

Because of this, I'd recommend that you ensure that you understand the basics of writing COM client code - e.g. You should understand CoCreateInstance, QueryInterface and smart pointers. ATL Internals (search on Amazon) is the essential reference on COM, but it is heavy going.

WTL wraps the detail of creating the ribbon and accessing it, but WTL was made for COM programmers looking for a windowing API, so it's not an easy API to begin with if you don't have experience of COM programming with ATL.

WTL supports the latest windows features, like ribbons etc. Don't expect any books on the subject though, there aren't any. M$ open sourced WTL some years ago, so the code is available to read, so you can figure out how everything works by reading the code. It's quite advanced though, you may want to look at it after you've had a look at the alternatives first.

Google uses WTL for the UI for Chrome.

I suspect you should Start with Ivor Horton's beginning Visual C++ 2010, it'll be a good all round introduction.

If you're looking for a great programming book for windows though, you can't do better than windows via c/c++ by Jeff richter - by far the best windows coding book I've ever bought.

If you are interested in WTL, then look at Michael dunn's series wtl for mfc programmers on code project.

Finally, there is no one book that hand hold the would be c++ GUI developer through all this, and that's a big gap in the market. I've often wondered why no one has picked up on this, given the popularity of c++

What are most important things you know about templates: hidden features, common mistakes, best and most useful practices, tips...common mistakes/oversight/assumptions

I am starting to implement most of my library/API using templates and would like to collect most common patterns, tips, etc., found in practice.

Let me formalize the question: What is the most important thing you've learned about templates?

Please try to provide examples -- it would be easier to understand, as opposed to convoluted and overly dry descriptions

Thanks

I'd have to say Coplien's Curiously Recurring Template Pattern (CRTP) is the one template trick that I find myself reaching for over & over again. Essentially it allows you to inject statically customized functionality into a derived class by inheriting from a base class that is parameterized on the derived class name. Mind boggling, but amazingly useful (some call it static polymorphism).

Also, I'll second Neil Butterworth's advice to read "C++ Templates" and throw in Alexandrescu's Modern C++ Design.

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

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

Large Scale C++ Design by John Lakos.

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

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

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

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

Alexandrescu: Modern C++ Design

Abrahams&Gurtovoy: C++ Template Metaprogramming

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

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

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

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

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

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

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

EDIT: I'm working with C++.

So, I am creating methods/functions to test intersection between shapes. I essentially have this:

class Shape {};

class Rectangle : public Shape {};

class Circle : public Shape {};

class Line : public Shape {};

Now, I need to decide on the best way to write the actual methods/functions to test intersection. But all my shapes will be stored in a list of Shape pointers, so I will be calling a method/function of the basic form:

bool intersects (Shape* a, Shape* b);

At that point, I need to determine which types of shapes 'a' and 'b' are, so I can properly detect collisions. I can easily do one of them, by just using some virtual methods:

class Shape
{
    virtual bool intersects (Shape* b) = 0;
}

That would determine one of the shapes ('a' is now 'this'). However, I would still need to get the type of 'b'. The obvious solution is to give Shape an 'id' variable to classify which shape it is, and then 'switch' through those, and then use dynamic_cast. However, that is not very elegant, and it feels like there should be a more OO way to do this.

Any suggestions?

Andrei Alexandrescu detailed this problem in his classic Modern C++ Design. The companion library Loki contains the the implementation for Multi-Methods.

Update

Loki provides three implementations of Multi-Methods, depending on the user's needs. Some are for simplicity, some are for speed, some are good for low coupling and some provide more safety than others. The chapter in the book spans nearly 40 pages, and it assumes the reader is familiar with many of the book's concepts -- if you are comfortable using boost, then Loki may be down your alley. I really can't distill that to an answer acceptable for SO, but I've pointed you to the best explanation of the subject for C++ that I know of.

Imagine I have abstract base class Shape, with derived classes Circle and Rectangle.

class Shape {};
class Circle : public Shape {};
class Rectangle : public Shape {};

I need to determine if two shapes are equal, assuming I have two Shape* pointers. (This is because I have two instances of vector<Shape*> and I want to see if they have the same shapes.)

The recommended way to do this is double dispatch. What I've come up with is this (greatly simplified here, so that shapes are equal to all other shapes of the same type):

class Shape {
public:
    virtual bool equals(Shape* other_shape) = 0;
protected:
    virtual bool is_equal(Circle& circle) { return false; };
    virtual bool is_equal(Rectangle& rect) { return false; };
    friend class Circle;    // so Rectangle::equals can access Circle::is_equal
    friend class Rectangle; // and vice versa
};

class Circle : public Shape {
public:
    virtual bool equals(Shape* other_shape) { return other_shape->is_equal(*this); };
protected:
    virtual bool is_equal(Circle& circle) { return true; };
};

class Rectangle : public Shape {
public:
    virtual bool equals(Shape* other_shape) { return other_shape->is_equal(*this); };
protected:
    virtual bool is_equal(Rectangle& circle) { return true; };
};

This works, but I have to add a separate equals function and friend declaration in Shape for each derived class. Then I have to copy-paste the exact same equals function into each derived class, too. This is an awful lot of boilerplate for say, 10 different shapes!

Is there a simpler way to do it?

dynamic_cast is out of the question; too slow. (Yes, I benchmarked it. Speed matters in my app.)

I tried this but it doesn't work:

class Shape {
public:
    virtual bool equals(Shape* other_shape) = 0;
private:
    virtual bool is_equal(Shape& circle) { return false; };
};

class Circle : public Shape {
public:
    virtual bool equals(Shape* other_shape) { return other_shape->is_equal(*this); };
private:
    virtual bool is_equal(Circle& circle) { return true; };
};

class Rectangle : public Shape {
public:
    virtual bool equals(Shape* other_shape) { return other_shape->is_equal(*this); };
private:
    virtual bool is_equal(Rectangle& circle) { return true; };
};

equals() always returns false, even on identical shapes. It seems dispatch is always choosing the is_equal(Shape&) base function, even when a "more specific" match is available. This probably makes sense but I don't understand C++ dispatch well enough to know why.

Double-dispatch has been well studied. The generalization of double-dispatch is called a "multi-method".

Chapter 11 of Modern C++ Design addresses this issue in detail. The approach using dynamic_cast<> that you described is in section 11.3 "Double Switch-on-Type: Brute Force". The author even describes how to automate most of the work and automatically generate the symmetric overloads. Then, the author introduces a logarithmic dispatch based on std::map<> and std::type_info. Finally, the section ends with "Constant-Time Multimethods: Raw Speed" that's (roughly) based on a matrix of callback functions.

The presented solution includes lengthy explanations on handling functors and casts to avoid nasty pitfalls in presence of multiple (and virtual) inheritance.

If you consider implementing multi-methods in C++, I stronly recommend that you read the book and implement the proposed solution.

Is there anyway to restrict the size of an array when passed as an argument to a function?

I mean is something like this possible?

/*following will lead to compile time error */

template<typename T, size_t n>=20> // or template<typename T,size_t n<=20>
void func(T (&a)[n])
{
   // do something with a

}

I want the size of my array to be at least(or at most) n(n can have any value).

For example:

When n=20 I must pass an array with at least(or at most) 20 elements. Is there any way in C++ for this?

GF's answer is correct, if you want more features or decisions points at compile time, you might want to look at boost::mpl. C++ Template Metaprogramming outlines what is possible with boost::MPL and how it was designed. Modern C++ design, which is not related to MPL, goes into design techniques which leverage compile time polymorphism

I am reading Modern C++ Design Generic Programming and Design Patterns Applied by Andrei Alexandrescu and chapter 11 on multimethods deals exactly with the problem I am trying to solve. All source code from the book is published in a library named Loki.

The problem is that the book is fairly old (2001) and deals with restrictions that are no longer true in C++11 (e.g. that the number of template parameters cannot be variable). I tried to look up if Loki has been rewritten using C++11, but the last modification is dated 2009 and there are no updates on Andrei Alexandrescu's home page. However, after doing some research I have the impression that Loki is something like Boost in the sense that it gets incorporated into the standard library.

Has the multimethod idiom or some of its parts been adopted into C++11?

It's not in the standard but would be reasonably easy to build using a map of function objects indexed by a pair of typeids.

For completeness, here's my first attempt:

#include <iostream>
#include <typeinfo>
#include <typeindex>
#include <map>
#include <functional>
#include <memory>

struct Animal {
    virtual std::type_index type() const = 0;
};

template <class T> struct AnimalImpl : public Animal {
    std::type_index type() const override {
        return typeid(T);
    }
};

struct Dog : AnimalImpl<Dog> {

};

struct Cat : AnimalImpl<Cat> {

};

struct Mouse : AnimalImpl<Mouse> {

};

using Types = std::tuple<std::type_index, std::type_index>;
using Outcome = std::function<void (Animal&, Animal&)>;
using DispatchMap = std::map<Types, Outcome>;

using namespace std;


void catVDog(Animal& cat, Animal& dog) {
    cout << "dog wins\n";
}

void catVMouse(Animal& cat, Animal& mouse)
{
    cout << "cat wins\n";
}

DispatchMap makeOutcomes()
{
    DispatchMap result;
    result.emplace( make_pair( Types {typeid(Cat), typeid(Dog)}, catVDog) );
    result.emplace( make_pair( Types {typeid(Dog), typeid(Cat)}, 
        [](Animal&a1,Animal&a2) { return catVDog(a2,a1); }) );

    result.emplace( make_pair( Types {typeid(Cat), typeid(Mouse)}, catVMouse) );
    result.emplace( make_pair( Types {typeid(Mouse), typeid(Cat)}, 
        [](Animal&a1,Animal&a2) { return catVMouse(a2,a1); }) );
    return result;
}

const DispatchMap outcomes = makeOutcomes();

void fight(Animal& a1, Animal& a2)
{
    auto it = outcomes.find(Types{ a1.type(), a2.type() });
    if (it == outcomes.end()) {
        cout << typeid(a1).name() << " " << typeid(a2).name() << " ";
        std::cout << "no fight\n";
    }
    else {
        it->second(a1, a2);
    }
}


int main()
{
    unique_ptr<Animal> cat { new Cat {} };
    unique_ptr<Animal> dog { new Dog {} };
    unique_ptr<Animal> mouse { new Mouse {} };

    fight(*cat, *dog);
    fight(*cat, *mouse);
    fight(*dog, *cat);
    fight(*dog, *mouse);

   return 0;
}

I have a Visual Studio 2008 C++ application where I'm using a custom allocator for standard containers such that their memory comes from a Memory Mapped File rather than the heap. This allocator is used for 4 different use cases:

  1. 104-byte fixed size structure std::vector< SomeType, MyAllocator< SomeType > > foo;
  2. 200-byte fixed size structure
  3. 304-byte fixed size structure
  4. n-byte strings std::basic_string< char, std::char_traits< char >, MyAllocator< char > > strn;

I need to be able to allocate roughly 32MB total for each of these.

The allocator tracks memory usage using a std::map of pointers to allocation size. typedef std::map< void*, size_t > SuperBlock; Each SuperBlock represents 4MB of memory.

There is a std::vector< SuperBlock > of these in case one SuperBlock isn't enough space.

The algorithm used for the allocator goes like this:

  1. For each SuperBlock: Is there space at the end of the SuperBlock? put the allocation there. (fast)
  2. If not, search within each SuperBlock for an empty space of sufficient size and put the allocation there. (slow)
  3. Still nothing? allocate another SuperBlock and put the allocation at the start of the new SuperBlock.

Unfortunately, step 2 can become VERY slow after a while. As copies of objects are made and temporary variables destroyed I get a lot of fragmentation. This causes a lot of deep searching within the memory structure. Fragmentation is in issue as I have a limited amount of memory to work with (see note below)

Can anybody suggest improvements to this algorithm that would speed up the process? Do I need two separate algorithms (1 for the fixed-size allocations and one for the string allocator)?

Note: For those that need a reason: I'm using this algorithm in Windows Mobile where there's a 32MB process slot limit to the Heap. So, the usual std::allocator won't cut it. I need to put the allocations in the 1GB Large Memory Area to have enough space and that's what this does.

Can you have a separate memory allocation pool for each different fixed-size type you are allocating? That way there won't be any fragmentation, because the allocated objects will always align on n-byte boundaries. That doesn't help for the variable-length strings, of course.

There's an example of small-object allocation in Alexandrescu's Modern C++ design that illustrates this principle and may give you some ideas.

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

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

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

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

Read :

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

Then if you want to go farther, read :

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

I'm making a game GUI API where each widget inherits from the Widget class. I was thinking, when others make there own widgets, they might not be fully satisfied with the base class. They might want to add getTheme() for example. Would it be a good idea to make all my widgets virtually inherit from Widget then so that this is possible?

Thanks

To resolve a diamond-shaped inheritance problem. (B and C both inherit from A. What happens to A's attributes in D that itself inherits from B and C?)

A client of your library could see a RedWidget and a FlyingWidget, and might want to combine them into a RedFlyingWidget.

User would have to specify one of the base classes to be virtual when inheriting. But that is not responsibility of a library maker.

OOP flows better with single-implementation inheritance, so that's what I'd use throughout a library.

There are also "upside-down inheritance" trees, as described by Alexandrescu's excellent "Modern C++ Design." They allow clients to pull in more functionality in a form of mix-ins that are called policies.

Programming with policies allows for greater ability to combine functionality, at the expense of syntactical cleanliness. Think STL implementation, for example.

Say you have a class who's job it is to connect to a remote server. I want to abstract this class to provide two versions, one that connects through UDP and the other through TCP. I want to build the leanest runtime code possible and instead of using polymorphism I am considering templates. Here is what I'm envisioning but I'm not sure it's the best way of doing this:

class udp {};
class tcp {};

template<class T,typename X>
class service
{
private:
  // Make this private so this non specialized version can't be used
   service();
};

template<typename X>
class service<udp, X>
{
private:
   udp _udp;
   X _x;
};

template<typename X>
class service<tcp, X>
{
private:
   tcp _tcp;
   X _x;
};

So the end benefit is that the genericness of T is still available, but the very different code required to setup a UDP or TCP connection has been specialized. I suppose you could put it both into one class, or provide another class that adheres to some pure virtual interface for setting up the network connection, like IConnectionManager.

But this does leave the problem of the code for the generic T now having to be written in and maintained in both specialized versions, where they are ultimately the same. How best to address this? I have a feeling I am going about this all wrong.

This can be best done using a policy for the transport protocol:

template<typename Transport>
class service : Transport {
public:
    typedef Transport transport_type;

    // common code
    void do_something() { 
        this->send(....);
    }
};

class tcp {
public:
    void send(....) {

    }
};

class udp {
public:
    void send(....) {

    }
};

typedef service<tcp> service_tcp;
typedef service<udp> service_udp;

Note that this is also polymorphic. It's called compile time polymorphism. Putting the policy into a base class will benefit from the Empty-Base-Class-Optimization. That is, your base class does not need to take any space. Putting the policy as a member has the other drawback that you always have to delegate stuff to that member, which can become annoying with time. The book Modern C++ Design describes this pattern in-depth.

Ideally, the transport protocol doesn't need to know anything about the protocol above it. But if for some reason you have to get some information about it, you can use the crtp pattern wiki:

template<template<typename Service> class Transport>
class service : Transport<service> {

    // since we derive privately, make the transport layer a friend of us, 
    // so that it can cast its this pointer down to us. 
    friend class Transport<service>;

public:
    typedef Transport<service> transport_type;

    // common code
    void do_something() { 
        this->send(....);
    }
};

template<typename Service>
class tcp {
public:
    void send(....) {

    }
};

template<typename Service>
class udp {
public:
    void send(....) {

    }
};

typedef service<tcp> service_tcp;
typedef service<udp> service_udp;

You don't have to put your templates into headers. If you explicitly instantiate them, you will gain faster compilation times, as much fewer code has to be included. Put this into service.cpp:

template class service<tcp>;
template class service<udp>;

Now, code that uses service does not need to know about the template code of service, since that code is already generated into the object file of service.cpp.

What is good book for industry level C++ programming? I am not looking for a beginners C++ book that talks about datatypes and control structures. I am looking for a more advanced book. For example, how to build system applications using C++. Any kind of guidance will be very helpful.

If you're looking for books on refining your craft in C++ as a language, you don't get much better than Scott Meyers' Effective C++ and More Effective C++ and Herb Sutter's Exceptional C++, More Exceptional C++ and Exceptional C++ Style. All are packed with invaluable information on bringing your facility with the language from the intermediate to the advanced level.

System-level programming is specific to operating system, so the books diverge based on your platform. Ones I've found very helpful (albeit not C++ specific) are: Windows System Programming, by Johnson M. Hart, Advanced Windows Debugging, by Mario Hewardt and Daniel Pravat, and Linux System Programming, by Robert Love.

All of these books (as well as Peter Alexander's excellent suggestion of Modern C++ Design) are available on O'Reilly's Safari service, which is a pretty cost-effective way of doing a lot of technical reading on the cheap and well worth checking out if you're considering going on a studying binge.

Lakos' Large Scale C++ Software Design is quite a good intermediate-advanced level book about C++ software architecture. It's a little out of date - predating widespread use of templates for example - but it is quite a good book on the subject.

Lakos worked for Mentor Graphics in the 1980s when first generation workstations were the technology du jour. This was an era when the difference in performance and memory footprint between C and C++ apps was regarded as significant. This 'old school' approach discusses efficient C++ systems architecture in some depth, which is a bit of a unique selling point for this book.

These are the best two books I have seen and read

Advanced C++ Programing Styles and Idioms

C++ Common Knowledge

Modern C++ Design by Andrei Alexandrescu is probably the most advanced C++ book out there. It's more about very advanced design patterns rather than building software.

I am trying to understand the real requirement of the usage of templates for policy based design. Going through the new templated designs in C++ I found that policy based class design is a highly suggested way of design which allows you to 'plug-in' different behaviors from policy classes. A minimal example is the following (a shortened version of the wiki):

template <typename LanguagePolicy>
class HelloWorld : private LanguagePolicy
{
    using LanguagePolicy::message;

public:
    // Behaviour method
    void run() const
    {
        // policy methods
        cout << message();
    }
};

class LanguagePolicyA
{
protected:
    std::string message() const
    {
        return "Hello, World!";
    }
};
//usage
HelloWorld<LanguagePolicyA> hello_worlda;
hello_worlda.run(); // prints "Hello, World!"

A quick analysis shows that just to get different plugable methods message() we are inheriting from a templated type whose definition can be provided by anyone (and identified at compile time).

But the same level of abstraction (and configurable methods) can be achieved without using a templated code and by the simple old school run time polymorphism as shown below.

class HelloWorld
{
    LanguagePolicy *lp; //list of all plugable class
public:
    HelloWorld(LanguagePolicy *lpn) {
        lp = lpn;
    }

    // Behaviour method
    void run() const
    {
        // policy methods
        cout << lp->message();
    }
};
class LanguagePolicy
{
protected:
    virtual std::string message() const;
};

class LanguagePolicyA: LanguagePolicy
{
protected:
    std::string message() const
    {
        return "Hello, World!";
    }
};
//usage
HelloWorld helloworld(new LanguagePolicyA);
helloworld.run();

Functionality and level of abstraction wise I don't see much of a difference in the two approach (even though the second approach has few extra lines of code for LanguagePolicy, I think it is needed for the other users to know the interface; otherwise understanding LanguagePolicy depends upon the documentation). But I do think the later to be 'clean' (coming from someone who has not used template much). This is because personally in my opinion non-templated classes are cleaner to look at and understand. An extremely good example is the popular library VTK (Visualization Tool Kit) which solves many different problems using the second approach. Even though there are not extensive documentations of VTK, most of us - its users, can just have a look into its class diagrams (sometimes they are quite big) and deduce behaviors of classes; and develop highly configurable and complicated pipelines in our application (can't imaging VTK to be template based :)). The opposite is libraries like STL/BOOST which I don't think is possible for anyone to be able to identify the working of the classes without the use of extensive documentation.

So my question is, is the template based policy design really superior (only in this scenario of policy based design) than virtual inheritance based? If so, when and why?

Both are valid ways of structuring, it actually depends on the requirements. E.g.

Runtime vs compile time polymorphism.

When do you want/can/have to achieve polymorphism ?

Performance overhead of virtual calls

Templates generate code that has no indirections

The actual usage of the class.

When you have to store heterogenous collections, a base class is needed, so you have to use inheritance.

A very good book on policy-based design (a bit dated but good nevertheless) is Modern C++ Design

Consider the following code where in I am calling a specific template function computecost depending on an enumerated value (category). In call cases the arguments of computecost are identical. There exists a one-one correspondence between the enum values and the C++ types. As the arguments to computecost are always identical across all the calls, is it possible to write the following code more compactly, ie. without repeating for every type/enum value.

mxClassID category = mxGetClassID(prhs);
    switch (category)  {
     case mxINT8_CLASS:   computecost<signed char>(T,offT,Offset,CostMatrix);   break;
     case mxUINT8_CLASS:  computecost<unsigned char>(T,offT,Offset,CostMatrix);  break;
     case mxINT16_CLASS:  computecost<signed short>(T,offT,Offset,CostMatrix);  break;
     case mxUINT16_CLASS: computecost<unsigned short>(T,offT,Offset,CostMatrix); break;
     case mxINT32_CLASS:  computecost<signed int>(T,offT,Offset,CostMatrix);  break;
     case mxSINGLE_CLASS: computecost<float>(T,offT,Offset,CostMatrix); break;
     case mxDOUBLE_CLASS: computecost<double>(T,offT,Offset,CostMatrix); break;
     default: break;
    }

Is there any reason why you are not using dynamic dispatch for the computecost function?

The simplest thing would be creating a inheritance hierarchy and just using dynamic dispatch. Each type in the hierarchy that would return mxINT8_CLASS as class id would implement computecost as a call to computecost<signed char>, and similarly for all of the other combinations.

If there is a strong reason not to use dynamic dispatch, you might consider implementing your own dynamic dispatch in different ways. The most obvious, simple and probably easier to maintain is what you already have. Slightly more complex can be done with macros, or you can try a templated version just for fun...

The macro solution (next one in complexity) could use a macro to define the relationship, another to define each case and then combine them:

#define FORALL_IDS( macro ) \
   macro( mxINT8_CLASS, signed char ); \
   macro( mxUINT8_CLASS, unsigned char ); \
// ...

#define CASE_DISPATCH_COMPUTECOST( value, type ) \
   case value: computecost<type>( T, offT, Offset, CostMatrix ); break

Combine:

switch ( category ) {
   FORALL_IDS( CASE_DISPATCH_COMPUTECOST );
};

I have seen this done in the past, and don't like it, but if there is a good amount of places where you need to map from the category to the type that could be a simple to write hard to maintain solution. Also note that the FORALL_IDS macro can be used to implement metaprogramming traits that map from the enum to the type and vice versa:

template <classId id>
struct type_from_id;
#define TYPE_FROM_ID( id, T ) \
   template <> struct type_from_id<id> { typedef T type; }
FORALL_IDS( TYPE_FROM_ID );
#undef TYPE_FROM_ID

template <typename T>
struct id_from_type;
#define ID_FROM_TYPE( id, T ) \
   template <> struct id_from_type<T> { static const classId value = id; }
FORALL_IDS( ID_FROM_TYPE );
#undef ID_FROM_TYPE

Note that this has a lot of drawbacks: macros are inherently unsafe, and this macros more so, as they define types and don't quite behave like functions, it is harder to find the appropriate amount of parenthesis to the arguments, which makes it more prone to all shorts of errors in text substitution... Macros don't know about contexts, so you might want to try and minimize the scope by undefining them right after use. Implementing the traits above is one good way to go about it: create the macro, use that to generate templated non-macro code, undef the macros. The rest of the code can use the templates rather than the macros to map from one to the other.

A different way of implementing dynamic dispatch is using a lookup table instead of the switch statement above:

typedef T function_t( T1, T2, T3 ); // whatever matches the `computecost` signature
function_t *lookup[ categories ];   // categories is 1+highest value for the category enum

You can manually initialize the lookup table, or you can use a macro as above, the complexity of the code will not change much, just move from the calling side to wherever the lookup table is initialized. On the caller side you would just do:

lookup[ mxGetClassID(prhs) ]( T, offT, Offset, CostMatrix );

Instead of the switch statement, but don't get fooled, the cost has not be removed, just pushed to the initialization (which might be good if you need to map more than one function, as you could create a struct of function pointers and perform the initialization of all at once, and there you have your own manually tailored vtable, where instead of a vptr you use the classId field to index.

The templated version of this is probably the most cumbersome. I would try to implementing just for the fun of it, but not really use it in production code. You can try building the lookup table from a template[1], which is fun as an exercise but probably more complex than the original problem.

Alternatively, you can implement a type-list type of approach (A la Modern C++ Design) and in each one of the nodes dispatch to the appropriate function. This is probably not worth the cost, and will be a nightmare to maintain in the future, so keep away from it from production code.

To sum up:

Just use the language dynamic dispatch, that is your best option. If there is a compelling reason not too, balance the different options and complexities. Depending on how many places you need to perform the dispatch from classId to X (where X is computecost here but could be many more things), consider using a hand tailored lookup table that will encapsulate all X operations into a function table --note that at this point, whatever the motives to avoid the vtable might have gone away: you are manually, and prone to errors implemented the same beast!

[1] The complexity in this case is slightly higher, because of the mapping from the enum to the types, but it should not be much more complex.

From my understanding partial classes are a bit frowned upon by professional developers, but I've come over a bit of an issue;

I have made an implementation of the RichTextBox control that uses user32.dll calls for faster editing of large texts. That results in quite a bit of code. Then I added spellchecking capabilities to the control, this was made in another class inheriting RichTextBox control as well. That also makes up a bit of code.

These two functionalities are quite separate but I would like them to be merged so that I can drop one control on my form that has both fast editing capabilities and spellchecking built in. I feel that simply adding the code form one class to the other would result in a too large code file, especially since there are two very distinct areas of functionality, so I seem to need another approach.

Now to my question; To merge these two classes should I make the spellchecking RichTextBox inherit from the fast edit one, that in turn inherits RichTextBox? Or should I make the two classes partials of a single class and thus making them more “equal” so to speak?

This is more of a question of OO principles and exercise on my part than me trying to reinvent the wheel, I know there are plenty of good text editing controls out there. But this is just a hobby for me and I just want to know how this kind of solution would be managed by a professional.

Thanks!

I am not entirely sure if I understand what you are trying to do, but as it seems to me, you are just looking for the Decorator design pattern. If this does not solve your problem enough and you are really thinking about composing classes from traits, look at Policy based design, although I am not so sure how much of that is possible to implement in C#. There is also that book - Modern C++ design which is a proponent of Policy based design, however it discusses the trade-offs for what you call partial classes versus (multiple) inheritance. The problem with chained inheritance is in deciding the order, because that order cretes strong dependencies and if you add SpellChecking to RichTextEdit, you would encounter a problem once you want to use SpellChecking for e.g. SearchBox, which might be SimpleEdit, but it would be nice to provide spellchecking for users... I hope this helps at least a bit.

I may be asking this in a odd way, but I'm not sure how else to ask.

I want to have a list of classes, not objects. This way I can call static functions without have to create the object.

What you are looking for are boost typelists. I would however not recommend diving into the Boost MPL if you are not already very experienced with templates, and know how many of their intricacies work.

Now for a simple home-made implementation:

struct Null {};

template <typename Type, typename Next>
struct List
{
  typedef Type Type;
  typedef Next Next;
};

//Now you can make lists like so:
typedef List<int, List<float List<short, Null> > > MyList;

From there use recursive Templated implementations to call the static methods you want.

If you want more information on these kinds of techniques, you should read Modern C++ Design

As pointed out by this post, in 'Modern C++ Design - Generic Programming and Design Patterns Applied', Andrei Alexandrescu uses classes with template template parameters to implement the policy pattern:

// Library code
template <template <class> class CreationPolicy>
class WidgetManager : public CreationPolicy<Widget>
{
   ...
};

Now, suppose that the policy class has a state (i.e. it has non-static members) and that the host class stores an object of the policy class:

// Library code
template <template <class> class Logger>
struct Algorithm
{
   Algorithm(Logger<Event> &logger) : logger_(logger) {}
   ...
   private:
       Logger<Event> &logger_; 
};

The user will probably write something like this:

using MyLogger = ConcreteLogger<MyEvent>;
MyLogger log;
Algorithm<ConcreteLogger> alg(log);

Since the user needs to instantiate ConcreteLogger, is there any remaining advantage in using template template parameter in this case?

Can a singleton class be inherited. if yes, then how can we do it?

**EDIT:***I mean to say that if we have a class which uses singleton design pattern,then can it be inherited?*

It depends on how is your implementation for the design pattern. The simplest form is to make a class like this:

class MySingleton
{
    public:
        static MySingleton &getInstance()
        {
            static MySingleton instance;            
            return instance;
        }
    private:
        MySingleton();
        ~MySingleton();
};

In this case, it can't be inherited because the derived class has no access to its constructor. You could make the constructor protected, but this will enable other derived classes to be non-singleton at will, which can be messy from a design perspective. But usually this simple form is not the preferred way to implement singletons since you have not much control about its lifetime and it's difficult to properly handle dependencies between singletons - not to mention possible multithreading issues. The book Modern C++ Design (http://www.amazon.com/Modern-Design-Generic-Programming-Patterns/dp/0201704315/ref=sr_1_1?ie=UTF8&s=books&qid=1270652521), among others, has better implementations; they are template-based and the template instantiation is what makes the object a singleton (and its parameter is the class that will be made singleton). This makes easier to do what you want, since the 'singleton-ness' is detached from the class itself. But nonetheless I think you'd need some policy (possibly enforced by code) to avoid that some class derived from a singleton would be non-singleton, which is difficult to implement.

My recommendation would be to have abstract base classes as ancestors for your singletons, and put the commom behaviour in them, not in the singleton itself, and have the singleton always as the 'final' class (borrowing this meaning from Java).

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 a templated matrix class that I explicitly instantiate for various POD types and custom class types. Some of the member functions however don't make sense for a few of such custom types. For example:

Matrix<int> LoadFile(....); // This makes sense
Matrix<My_custom_class> LoadFile(...); //This doesn't make sense in the context of the custom class

Can I prevent the instantiation of the LoadFile function (which is a member function) for Matrix objects of select types? So far I have avoided the issue by making LoadFile a friend function and then explicitly controlling its instantiation. But I want to know if I can do this when LoadFile is a member function of Matrix.

If you could use the TypeLists from the ( http://www.amazon.com/Modern-Design-Generic-Programming-Patterns/dp/0201704315 ) - Loki you could implement something like:

template<bool>
struct Static_Assert;

template<>
struct Static_Assert<true>{};

class B{};

template<typename T>
class A{
public:
  A(){
    Static_Assert< 0 == utils::HasType<T, TYPELIST_2(B,int) >::value >();
  }
};

Then your HasType would be something like:

template<typename T, typename TList>
struct HasType{
  enum { value = 0+HasType< T, typename TList::Tail >::value };
};

template<typename T>
struct HasType< T, NullType >{
  enum { value = 0 };
};

template<typename T, typename U>
struct HasType< T, TypeList<T, U> >{
  enum { value = 1 };
};

In the list you can add the classes which you would like prevent to be passed as the template parameters.

I have circles, boxes and lines. And now I want to implement collision detection between them. This means that I have to have a function for each combination of two kinds of shapes. Of course I can use the same for line vs circle and circle vs line, but I think my point still stands. What's the most elegant way to implement this in C++?

In the Modern C++ Design book, Multimethods chapter explains how to implement them and documents how to use [implementation provided by Loki library][2]. There is also Boost.Multimethod proposal, but it's not there yet. The book demonstrates the power of multimethods exactly on the topic of object collision.

In the boost graph library, there are property maps used. For an example, consider this link about properties. You can add multiple properties list like:

typedef property<vertex_distance_t, float, 
    property<vertex_name_t, std::string> > VertexProperty;

My questions are:

  • Is there a name for this "list of templates" concept, so I can google it?
  • Are there similar advanced template structures, like arrays or trees?
  • Do you have a good book or weblink explaining it?

Note: I need a solution without C++11, though C++11 would be interesting, too.

This type of template composition is called base class chaining.

It specifically works nicely to

  • profit from empty baseclass optimizations
  • making it relatively easy to support open-ended lists of mixins, even on compilers that don't directly support variadics yet

    Edit In fact, indeed this was how typelists were usually implemented before the advent of (c++0x) variadics (Modern C++ Design)

References:

Related:

I saw Scott Meyers' "Effective C++" third edition book having a small section on "Template Programming".

Any other book/links containing information on "effective" usage of templates ?

Scott Meyers deals with the Standard Template Library in Effective STL. That may be relevant for you.

I like Modern C++ Design: Generic Programming and Design Patterns Applied. I found it very well written and clear. Contains a few advanced topics.

alt text

A rarely mentioned but solid book is C++ Common Knowledge by Stephen C. Dewhurst. "Among the first users of C++ at Bell Labs", Dewhurst gives the book a somewhat deceptive title because he actually covers quite a bit of advanced material in particular in regards to templates.

Dewhurst's book is organized similarly to Meyers's with 63 "Items" that you can usefully read on their own. On templates you should look over items 45-59 (about 70 pages of reading).

alt text

I want to know if there is a design pattern for specifying options to a set of algorithms. I am using C++. Let me describe my problem. I am having a set of algorithms and these algorithms have different options. I want to design a single point access to these algorithms. Something similar to a strategy pattern. This single point access is a controller class which takes input as a generic options class. Depending upon the options, a suitable algorithm will be used. I want to generalize these options so that i can extend algorithms and the client. Thanks, Amol

I agree with Konrad on policy-based design. I also recommend Modern C++ Design: Generic Programming and Design Patterns Applied. After this book your vision of C++ will be changed forever ;)

Suppose I want test something with vector<int>, vector<bool>, vector<string>. I want to write something like this:

for(type T in {int, bool, string}){
   vector<T> v;
   for(int i = 0; i < 3; ++i){
       v.push_back(randomValue<T>());
   }
   assert(v.size() == 3);
}

I know there isn't such feature in the language but is it possible to emulate somehow? Is there this functional in some library, for example boost?

Boost.MPL

It is possible to accomplish with typelists - they are discussed in details in Modern C++ Design: Generic Programming and Design Patterns Applied by Andrei Alexandrescu

Check Boost.MPL library. For instance - boost::mpl::for_each

LIVE DEMO

#include <boost/exception/detail/type_info.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/vector.hpp>
#include <iostream>
#include <cassert>
#include <vector>
#include <string>

using namespace boost;
using namespace std;

template<typename T>
T randomValue()
{
    return T();
}

struct Benchmark
{
    template<typename T>
    void operator()(T) const
    {
        cout << "Testing " << type_name<T>() << endl;
        vector<T> v;
        for(int i = 0; i < 3; ++i)
        {
           v.push_back(randomValue<T>());
        }
        assert(v.size() == 3);
    }
};

int main()
{
    mpl::for_each<mpl::vector<int, bool, string>>(Benchmark());
}

Output is:

Testing int
Testing bool
Testing std::string

C++11 Variadic Templates

Another option is to use C++11 variadic templates:

LIVE DEMO

#include <boost/exception/detail/type_info.hpp>
#include <iostream>
#include <cassert>
#include <vector>
#include <string>

using namespace boost;
using namespace std;

template<typename T>
T randomValue()
{
    return T();
}

struct Benchmark
{
    template<typename T>
    void operator()(T) const
    {
        cout << "Testing " << type_name<T>() << endl;
        vector<T> v;
        for(int i = 0; i < 3; ++i)
        {
           v.push_back(randomValue<T>());
        }
        assert(v.size() == 3);
    }
};

template<typename ...Ts,typename F>
void for_each(F f)
{
    auto &&t = {(f(Ts()),0)...};
    (void)t;
}

int main()
{
    for_each<int, bool, string>(Benchmark());
}

Possible Duplicate:
What is the best source to learn C++?

Hi Guys,

Fortunately, it looks like I have start learning C++ and make myself well equipped, such that I can involve myself into some serious stuff (coding I mean).

I do already have working knowledge/experience of Perl and C#. With this, I was wondering how hard/easy it will be for me to get well versed with C++ in less than 5 months ... spending max 2 hours/day.

Please, need your suggestion.

Thanks, Rahul

Altough learning C++ is probably a life long endeavor you can get up to speed in a five months time frame but don't expect to be writing libraries for boost by then.

Bjarne Stroustrup book The C++ Programming Language is probably the best start point. Bjarne also writes in a nice to read way, you're going to enjoy it.

Scott Meyers Effective C++ and More Effective C++ are also must read books. Modern C++ Design by Andrei Alexandrescu is one of the best C++ books ever written, I believe.

Since a language without a platform is a dry place, you must take into account some time to learn the hopes in wherever platform you want to work with like Qt, and son.

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 am trying to implement a factory for two classes Circle, Square both of which inherits from Shape.

class Shape {
public: 
    virtual static
    Shape * getInstance() = 0;

};

class Circle : public Shape {        
public:
    static const std::string type;

    Shape * getInstance() {
        return new Circle;
    }
};
const std::string Circle::type = "Circle";

class Square : public Shape {        
public:
    static const std::string type;

    Shape * getInstance() {
        return new Square;
    }
};
const std::string Square::type = "Square"; 

I want to now create a map with key as shape type (string) and value as a function pointer to getInstance() of the corresponding derived class. Is it possible?

Thanks, Kiran

Although not much relevant to your question, but if you are interested in modern C++ design (factories, smart pointers, etc.), you may like to check this book:

http://www.amazon.co.uk/Modern-Design-Applied-Generic-Patterns/dp/0201704315/ref=sr_1_20?s=books&ie=UTF8&qid=1293359949&sr=1-20

It talk about factories, how to design them, etc.

PS: I am not the author of the book, nor I have been given any thing in return for posting this answer :-)

I have a bunch of algorithms and collections, and I am using a Policy Based design (see the book Modern C++ Design) to deal with arbitrary combinatorial complexity. This is great, but in order to prevent the destruction of the Host class by using the pointer to a policy, 1 suggests to make the destructors of policied protected. However, if I make the Algorithm and Collection destructors protected, I cannot use them on their own, but only as policies. Also, I don't see the benefits of the Policy Based design, compared to a Generic Factory Pattern...

Here is the model of the code:

#include <iostream>

template<class Collection>
class AlgorithmOne
{
    public: 
        void doSomethingWithData(Collection& data) 
        {
            // Use Collection iterators to build up an algorithm. 
        }
};

template<class Collection>
class AlgorithmTwo
{
    public: 
        void doSomethingWithData(Collection& data) 
        {
            // Use Collection iterators to build up an algorithm. 
        }
};

template<class Collection>
class AlgorithmThree
{
    public: 
        void doSomethingWithData(Collection& data) 
        {
            // Use Collection iterators to build up an algorithm. 
        }
};


template<class Element>
class CollectionOne
{
    public: 
        typedef Element ElementType;

};

template<class Element>
class CollectionTwo
{
    public: 
        typedef Element ElementType;

};

template<class Element>
class CollectionThree
{
    public: 
        typedef Element ElementType;

};

template<typename HostTraits>
class HostInheritsData
:
    public HostTraits::Collection, 
    public HostTraits::Algorithm
{
    public: 
        typedef HostTraits Traits;

        using Traits::Algorithm::doSomethingWithData;

        void doSomethingWithData() 
        {
            doSomethingWithData(*this);
        }
};

template<typename HostTraits>
class HostCompositsData 
:
    public HostTraits::Algorithm
{
    typename HostTraits::Collection data_;

    public: 
        typedef HostTraits Traits;

        using Traits::Algorithm::doSomethingWithData; 

        void doSomethingWithData() 
        {
            doSomethingWithData(data_);
        }

        // Clumsy and breaking encapsulation
        typename HostTraits::Collection& data()
        {
            return data_;
        }
};

template<typename HostTraits>
class GenericStrategy
{
    typename HostTraits::Collection data_; 
    typename HostTraits::Algorithm algorithm_; 

    public: 

        void doSomethingWithData() 
        {
            algorithm_.doSomethingWithData(data_);
        }
};

class ElementOne {}; 
class ElementTwo {}; 
class ElementThree {}; 

struct MyConfig
{
    typedef ElementOne                  Element;
    typedef CollectionThree<Element>      Collection;
    typedef AlgorithmOne<Collection>  Algorithm;
};

int main(int argc, const char *argv[])
{
    HostInheritsData<MyConfig> hostInherits;
    hostInherits.doSomethingWithData(); 

    // This must be a mistake, are policies meant to be used this way? 
    hostInherits.doSomethingWithData(hostInherits); 

    HostCompositsData<MyConfig> hostComposits;
    hostComposits.doSomethingWithData(); 

    // Clumsy to use, not intuitive and breaking encapsulation.
    hostComposits.doSomethingWithData(hostComposits.data()); 

    // Combinatorics are there, I can combine whatever I want in MyConfig as for
    // policies, but I can also have global Algorithm and Collection objects 
    // (no protected destructors).
    GenericStrategy<MyConfig> strategy; 
    strategy.doSomethingWithData(); 

    return 0;
}

Here are my questions:

I am customizing the structure of a Host class using policies, how can I trully enrich the interface of the Host class, when every realistic Algorithm requires a Collection to work on, and the Collection is encapsulated in the host?

When I compare the Policy Based Design together with a Generic Factory, doesn't the Generic Factory bring me the same combinatorial complexity? It seems that using the Generic Factory is better since I can interchange Element, Container and Algorithm in all possible combinations as well, and I can still have public destructors for all the Policies, which allows me to combine them in any way I want, e.g. a global combination of Element, Collection and Algorithm.

It seems to me that the Enriched Policies become a problem as soon as the structure is customized. Even if I later on add a member function to an algorithm, it will probably have parameters related to Collection (e.g. Collection iterators): if the Host encapsulates Collection using composition, I need to ask it for the parameter of its own member function:

// Clumsy to use, not intuitive and breaking encapsulation.
hostComposits.doSomethingWithData(hostComposits.data());

and if the Host encapsulates the Collection using inheritance, it gets (to me at least) even weirder:

 // This must be a mistake, are policies meant to be used this way? 
    hostInherits.doSomethingWithData(hostInherits); 

Did I completely misunderstand Policy Based design (yet again), am I using the traits properly? Is the Generic Strategy Pattern a better choice in this case?

You might want to think carefully about the amount of coupling in your design. E.g. make sure that you really want your algorithms to take a Collection as template parameters. This introduces a coupling between the algorithm and the container it operates on. Take a look at the Standard Library: its algorithms are function templates taking iterators as template parameters. Iterators do not know anyting about the container (Collection in your vocabulary) they point too.

To do other things than iteration and access, algorithms take slightly more enriched types as parameters, e.g. back_inserters to accesss the push_back() member of a container. But in general -without prior knowledge- there is absolutely no need to pass the entire container interface to all algorithms. To do really container specific things, embedding the algorithm as a container member function (e.g. the sort() member function of std::list) is more appropriate.

For doing slightly different things, there are several overloads (e.g. of std::transform) of the same function name. Only if your algorithm needs to maintain state is it really necessary to make it a class template, and the preferable way is to make it a function object, i.e. containing an overloaded operator(), instead of a DoSomethingWithData() member function.

Your data is parameterized in the same way as the Standard Library: a class template with an Element as template parameter. The way to feed such data to the algorithms is to provide iterator access to your data in the form of begin() and end() member functions. The Standard containers (vector, map, unorderd_map etc.) also take policies as template parameters, e.g. an Allocator, Compare or Hash class through which you can customize your data's behavior. The Standard smart pointers take a Deleter policy parameter to customize their behavior.

In short: carefully check your design. What is it that you want to do? What does each component (algorith, data structure) need to know about the other? And can you get there with proper use of the Standard Library? It's a safe bet that most of the things you might want to are already coded in there, and you can concentrate on writing your application's logic, rather than the algorithmic or data structure details.

I have a singleton class, whose instance get initialized at global scope within the class's CPP file:

Singleton* Singleton::uniqueInstance = new Singleton();

Its header file looks like:

class Singleton {
public:
    static Singleton& getInstance() { return *uniqueInstance; }
    static bool destroyInstance() { delete uniqueInstance; }

private:
    //...
    //... typical singleton stuff
    static Singleton* uniqueInstance;
}; // end of class Singleton

I noticed that its destructor dodn't get executed during program termination, thus I added a public static interface Singleton::destroyInstance(), to be manually invoke by client code before the program exits, for instance deletion. This snippet is not the complete code, and assumed that there are other codes that dealing with thread safety issue. In this case, how can I make use of RAII to eliminate the need of introducing such an interface? Thanks for advice.

Singleton are easy to create, unless you are in a MultiThreaded environment. If you can, you'll want to make sure that only one thread is trying to create your singleton (and thus destroy it). Once created it may be used by multiple threads at once... though that may not be the best way to deal with this.

Anyway, a very simplistic option is thus:

class MySingleton
{
public:
  static MySingleton& Intance() { static MySingleton M_Instance; return M_Instance; }
private:
  MySingleton() {}
};

It works well as long as you're not using MI and you do not use the singleton during globals destructions. Also it does not work with VC2003 at least (used to instantiate one singleton for each library the method was called....), I don't know with more recent versions, we've stopped compiling on windows altogether a while ago.

Now, if you want to really learn more about Singleton:

  • instanciation and destruction issues
  • lifetime variety
  • threading safety

Alexandrescu concentrated on this for a full chapter in Modern C++ Design, if you don't have access to the book you can still read the code that resulted from the reflexion in Loki.

Also, you might simply use alternative approaches to the design. Singleton may make testing difficult, there have been interesting thoughts about this from the people that support Dependency Injection. Take a peek at Misko Hevery blog entry.

I just wonder after reading "template metaprogramming - concepts, tool and techniques" if the whole "high level" of metaprograming isn't just an art for an art?

What I'm getting at is, where and when will I have a need to iterate in compile time over a vector to find if some type is there? 5% of apps?

I'm not saying that all metaprogramming is useless, on the contrary - metafunctions like is_this or is_that I'm finding very useful indeed but I have serious problems with seeing practical use for like I've said before,iterating over a vector in order to find if a type is there (at compile time of course).

The iterating is very useful...if some other library is doing it for you. That was a major observation I made from reading the book "Modern C++ Design". But even then, I can't count on any C++ developer being familiar with the book or Loki library. Nor can I count on a dev team being willing to use that library. The visitor pattern was the coup de grace useage of those facilities, but I havn't had opportunity to use it yet.

This all translates to "yes," you are not going to have much use for it in practice. But it is an excellent "working of the mind" to go through.

I want to breakup a class so that its decoupled from the logic of performing certain task so that users can write new strategies as they wish to without interfering with the central model. So, I want to use templated strategy class but without having to have the user of the strategy to be templatised:

   class Model {  
     ...  
     boost::shared_ptr< Strategy < T > > m_pStrategy;  
     ...  
     public:  
     template <  typename T  >  
     void DoSomething() { m_pStrategy < T > ::DoSomething(); }  
    };  

I would like the DoSomething function to not be templated. Is there any other way I can achieve what I want to do here?

thanks.

It seems to me like what you want to implement is a Policy-Based Design. I'm not sure what Model and Strategy do exactly, but it seems like Model is the root class, and Strategy is the Policy class, which users would want to provide in some cases to perform special handling. It also seems like the only reason you keep a pointer to the Strategy<T> object around is so that you can call functions on it.

In this case, you can design your class like this:

template<class Strategy> 
class Model : public Strategy {  
 public:  
 void DoSomething() 
 { 
    // magic happens (we will fill this in shortly)
 };
};  

You call methods on the Strategy class to do your magic. By letting the users define their own Strategy class, you give them the opportunity to define their own "magic". You need to apply rules on what method the Strategy class will provide at a minimum, so that you can call those methods in Model.

For example, suppose Model is actually some kind of resource manager, capable of being a simple smart pointer, or something else like a resource manager for a Windows Critical Section. Let's rename Model to auto_resource and Strategy will become release_policy and will be responsible for releasing whatever resource was assigned to it. In that case, you might have:

class pointer_release_policy
{
public:
  template<class Object> void release(Object* obj) { delete obj; }  
};

template<class Managed, class release_policy>
class auto_resource : public release_policy
{
public:
  // ... ctors etc defined here
  ~auto_resource()
  {
    release_policy::release(managed_);
  }
private:
  Managed managed_;
};

Which you could use for std::string pointers like this:

typedef auto_resource<std::string*, pointer_release_policy> string_ptr;
string_ptr my_str;

...and when my_str falls off the stack, the release method will automatically be called.

Later you want to add a new policy for releasing Windows mutex HANDLEs:

class handle_release_policy
{
public:
  template<class Handle> void release(Handle h)
  { 
    CloseHandle(h); // this is a WINAPI function that deallocates the specified resource
  };
};

You can use this thusly:

typedef auto_resource<HANDLE, handle_resource_policy> handle_resource;
//... allocate & use the mutex...
handle_resource mutex = CreateMutex(0, 0, 0);

Of course, in order to flesh all this out you need to add functionality for assigning, copying, releasing etc the resources. Here is a complete working example that puts everything together. I've provided 2 sets of policies, one for Windows CRITICAL_SECTIONs, and another for SOCKETs:

class SimpleCopyPolicy
{
public:
    template<class Resource> Resource copy(const Resource& rhs) const { Resource ret = rhs; return ret; }
protected:
    ~SimpleCopyPolicy(){};
};

class CritsecReleasePolicy
{
public:
    template<class Handle> bool release(Handle& h)
    {
        DeleteCriticalSection(&h);
        return true;
    }
protected:
    ~CritsecReleasePolicy() {};
};

class CritsecLockPolicy  // CRITICAL_SECTION lock/unlock policies
{
public:
    template<class Handle> bool lock(Handle& h)
    {
        EnterCriticalSection(const_cast<CRITICAL_SECTION*>(&h));
        return true;
    }
    template<class Handle> bool unlock(Handle& h) 
    {
        LeaveCriticalSection(&h);
        return true;
    }
};


class SocketReleasePolicy
{
public:
    template<class Handle> bool release(Handle h) { return 0 != closesocket(h); }
protected:
    ~SocketReleasePolicy(){};
};

template<class Resource, typename ReleasePolicy, typename CopyPolicy = SimpleCopyPolicy>
class simple_auto_resource : public ReleasePolicy, public CopyPolicy
{
public:
    typedef simple_auto_resource<Resource,ReleasePolicy,CopyPolicy> base_type;

    simple_auto_resource() : res(0) {}
    simple_auto_resource(const Resource & r) : res(copy(r)) {}
    ~simple_auto_resource() { if(res) release(res); }

    void clear() { if(res) release(res); res = 0; }

    Resource& get() { return res; }
    const Resource& get() const { return res; }

    Resource detach() { Resource ret = res; res = 0; return ret; }

    operator const Resource&() const { return get(); }
    operator Resource&() { return get(); }

    base_type& operator=(const Resource& rhs) { clear(); res = copy(rhs); return * this; }

    template<class Comp> bool operator==(const Comp& rhs) const { return res == (Resource)rhs; }
    template<class Comp> bool operator!=(const Comp& rhs) const { return res != (Resource)rhs; }
    template<class Comp> bool operator<(const Comp& rhs) const { return res < (Resource)rhs; }
private:
    Resource res;
};

typedef simple_auto_resource<CRITICAL_SECTION, CritsecReleasePolicy> auto_critsec;
typedef simple_auto_resource<SOCKET,SocketReleasePolicy> auto_socket;

For more on policy-based design, see Modern C++ Design.

...

So I have the following project to accomplish. I'm undecided on how to design it though. Would love some advice.

It's basically a table archiver. Givend a certain condition you need to export those rows in another place. This place could be another database or an (s)ftp server. If you choose a database you need to create a table everytime you reach a certain limit (like no more than 50k rows per table), if you choose an (s)ftp server then you need to write a CSV or an XML and put the file there.

So we have these combinations:

  1. sql2CustomerSql
  2. sql2Oursql (for this we already class for connecting and getting some information base on system configuration)
  3. csv2ftp
  4. csv2sftp
  5. xml2ftp
  6. xml2sftp

Now, I see AbstractFactory pattern all over the place but based on what? My thinking is that I should have SQLWriter, XMLWriter, CSVWriter that inherits all from an abstract Writer class that implements some common policy like counting rows, getting common configuration parameters etc... Should I do the same for the Connection class/interface (because sql and (s)ftp are really different?

If you need more information just ask.

You might want to get hold of a copy of Modern C++ Design to get ideas on how to make a policy-based generic conversion tool. Below a very sketchy skeleton that is parameterized on two policies: the Format and the Connection.

template
<
    typename FormatPolicy,    // SQL, XML, CSV, provides row, config functionality
    typename ConnectionPolicy // SQL, FTP, provides open/close/read/write functionality
>
class ConversionTool
: 
    public FormatPolicy,
    public ConnectionPolicy
{
public:
    // your conversion interface here
    void operator()( /* your input */, /* your output */);
};

class SQLFormat { // SQL specific stuff } ;
class SQLConnection { // SQL specific stuff };

typedef ConversionTool<SQLFormat, SQLConnection> SQL2OurCustomerSQL;
SQL2OurCustomerSQL()(in_file, out_file); // for elsewhere declared in_file / out_file

This is my first program I really created besides hello world. The code is over 400 lines of code and wanted to know of new functions and what not that would help improve my code and my knowledge of C++. I figured I would just dive in and learn on my own instead of out of the book I have "Teach yourself C++ in one hour a day 6th edition".

What are some new functions I can learn that would improve my code?

// Runescape Mining Calculator

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int lvl;
    int exp;
    int result;

    cout << " \t\t\tRunescape Skill Calculator" << endl;
    cout << " Enter Target level: ";
    cin>>lvl;

    switch(lvl)
    {
                    case 2: cout << " What is your current experience? ";;
                    cin >> exp;
                    result=83 - exp;
                    break;
                    case 3: cout << " What is your current experience? ";
                    cin >> exp;
                    result=174 - exp;
                    break;
                    case 4: cout << " What is your current experience? ";
                    cin >> exp;
                    result=276 - exp;
                    break;
                    case 5: cout << " What is your current experience? ";
                    cin >> exp;
                    result=388 - exp;
                    break;
                    case 6: cout << " What is your current experience? ";
                    cin >> exp;
                    result=512 - exp;
                        break;                  
                    case 7: cout << " What is your current experience? ";
                    cin >> exp;
                    result=650 - exp;
                    break;                  
                    case 8: cout << " What is your current experience? ";
                    cin >> exp;
                    result=801 - exp;
                    break;                  
                    case 9: cout << " What is your current experience? ";
                    cin >> exp;
                    result=969 - exp;
                    break;                  
                    case 10: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1154 - exp;
                    break;
                    case 11: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1358 - exp;
                    break;
                    case 12: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1584 - exp;
                    break;
                    case 13: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1833 - exp;
                    break;
                    case 14: cout << " What is your current experience? ";
                    cin >> exp;
                    result=2107 - exp;
                    break;
                    case 15: cout << " What is your current experience? ";
                    cin >> exp;
                    result=2411 - exp;
                    break;
                    case 16: cout << " What is your current experience? ";
                    cin >> exp;
                    result=2746 - exp;
                    break;
                    case 17: cout << " What is your current experience? ";
                    cin >> exp;
                    result=3115 - exp;
                    break;
                    case 18: cout << " What is your current experience? ";
                    cin >> exp;
                    result=3523 - exp;
                    break;
                    case 19: cout << " What is your current experience? ";
                    cin >> exp;
                    result=3973 - exp;
                    break;
                    case 20: cout << " What is your current experience? ";
                    cin >> exp;
                    result=4470 - exp;
                    break;
                    case 21: cout << " What is your current experience? ";
                    cin >> exp;
                    result=5018 - exp;
                    break;
                    case 22: cout << " What is your current experience? ";
                    cin >> exp;
                    result=5624 - exp;
                    break;
                    case 23: cout << " What is your current experience? ";
                    cin >> exp;
                    result=6291 - exp;
                    break;
                    case 24: cout << " What is your current experience? ";
                    cin >> exp;
                    result=7028 - exp;
                    break;
                    case 25: cout << " What is your current experience? ";
                    cin >> exp;
                    result=7842 - exp;
                    break;
                        case 26: cout << " What is your current experience? ";
                    cin >> exp;
                    result=8740 - exp;
                    break;
                    case 27: cout << " What is your current experience? ";
                    cin >> exp;
                    result=9730 - exp;
                    break;
                    case 28: cout << " What is your current experience? ";
                    cin >> exp;
                    result=10824 - exp;
                    break;
                    case 29: cout << " What is your current experience? ";
                    cin >> exp;
                    result=12031 - exp;
                    break;
                    case 30: cout << " What is your current experience? ";
                    cin >> exp;
                    result=13363 - exp;
                    break;
                    case 31: cout << " What is your current experience? ";
                    cin >> exp;
                    result=14833 - exp;
                    break;
                    case 32: cout << " What is your current experience? ";
                    cin >> exp;
                    result=16456 - exp;
                    break;
                    case 33: cout << " What is your current experience? ";
                    cin >> exp;
                    result=18247 - exp;
                    break;
                    case 34: cout << " What is your current experience? ";
                    cin >> exp;
                    result=20224 - exp;
                    break;
                    case 35: cout << " What is your current experience? ";
                    cin >> exp;
                    result=22406 - exp;
                    break;
                    case 36: cout << " What is your current experience? ";
                    cin >> exp;
                    result=24815 - exp;
                    break;
                    case 37: cout << " What is your current experience? ";
                    cin >> exp;
                    result=27473 - exp;
                    break;
                    case 38: cout << " What is your current experience? ";
                    cin >> exp;
                    result=30408 - exp;
                    break;
                    case 39: cout << " What is your current experience? ";
                    cin >> exp;
                    result=33648 - exp;
                    break;
                    case 40: cout << " What is your current experience? ";
                    cin >> exp;
                    result=37224 - exp;
                    break;
                    case 41: cout << " What is your current experience? ";
                    cin >> exp;
                    result=41171 - exp;
                    break;
                    case 42: cout << " What is your current experience? ";
                    cin >> exp;
                    result=45529 - exp;
                    break;
                    case 43: cout << " What is your current experience? ";
                    cin >> exp;
                    result=50339- exp;
                        break;
                    case 44: cout << " What is your current experience? ";
                    cin >> exp;
                    result=55649 - exp;
                    break;
                    case 45: cout << " What is your current experience? ";
                    cin >> exp;
                    result=61512 - exp;
                    break;
                    case 46: cout << " What is your current experience? ";
                    cin >> exp;
                    result=67983 - exp;
                    break;
                    case 47: cout << " What is your current experience? ";
                    cin >> exp;
                    result=75127 - exp;
                    break;
                    case 48: cout << " What is your current experience? ";
                    cin >> exp;
                    result=83014 - exp;
                    break;
                    case 49: cout << " What is your current experience? ";
                    cin >> exp;
                    result=91721 - exp;
                    break;
                    case 50: cout << " What is your current experience? ";
                    cin >> exp;
                    result=101333 - exp;
                    break;
                    case 51: cout << " What is your current experience? ";
                    cin >> exp;
                    result=111945 - exp;
                    break;
                    case 52: cout << " What is your current experience? ";
                    cin >> exp;
                    result=123660 - exp;
                    break;
                    case 53: cout << " What is your current experience? ";
                    cin >> exp;
                    result=136594 - exp;
                    break;
                    case 54: cout << " What is your current experience? ";
                    cin >> exp;
                    result=150872 - exp;
                    break;
                    case 55: cout << " What is your current experience? ";
                    cin >> exp;
                    result=166636 - exp;
                    break;
                    case 56: cout << " What is your current experience? ";
                    cin >> exp;
                    result=184040 - exp;
                    break;
                    case 57: cout << " What is your current experience? ";
                    cin >> exp;
                    result=203254 - exp;
                    break;
                    case 58: cout << " What is your current experience? ";
                    cin >> exp;
                    result=224466 - exp;
                    break;
                    case 59: cout << " What is your current experience? ";
                    cin >> exp;
                    result=247886 - exp;
                    break;
                    case 60: cout << " What is your current experience? ";
                    cin >> exp;
                    result=273742 - exp;
                    break;
                    case 61: cout << " What is your current experience? ";
                    cin >> exp;
                    result=302288 - exp;
                    break;
                    case 62: cout << " What is your current experience? ";
                    cin >> exp;
                    result=333804 - exp;
                    break;
                    case 63: cout << " What is your current experience? ";
                    cin >> exp;
                    result=368599 - exp;
                    break;
                    case 64: cout << " What is your current experience? ";
                    cin >> exp;
                    result=407015 - exp;
                    break;
                    case 65: cout << " What is your current experience? ";
                    cin >> exp;
                    result=449428 - exp;
                    break;
                    case 66: cout << " What is your current experience? ";
                    cin >> exp;
                    result=496254 - exp;
                    break;
                    case 67: cout << " What is your current experience? ";
                    cin >> exp;
                    result=547953 - exp;
                    break;
                    case 68: cout << " What is your current experience? ";
                    cin >> exp;
                    result=605032 - exp;
                    break;
                    case 69: cout << " What is your current experience? ";
                    cin >> exp;
                    result=668051 - exp;
                    break;
                    case 70: cout << " What is your current experience? ";
                    cin >> exp;
                    result=737627 - exp;
                    break;
                    case 71: cout << " What is your current experience? ";
                    cin >> exp;
                    result=814445 - exp;
                    break;
                    case 72: cout << " What is your current experience? ";
                    cin >> exp;
                    result=899257 - exp;
                    break;
                    case 73: cout << " What is your current experience? ";
                    cin >> exp;
                    result=992895 - exp;
                    break;
                    case 74: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1096278 - exp;
                    break;
                    case 75: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1210421 - exp;
                    break;
                    case 76: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1336443 - exp;
                    break;
                    case 77: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1475581 - exp;
                    break;
                    case 78: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1629200 - exp;
                    break;
                    case 79: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1798808 - exp;
                    break;
                    case 80: cout << " What is your current experience? ";
                    cin >> exp;
                    result=1986068 - exp;
                    break;
                    case 81: cout << " What is your current experience? ";
                    cin >> exp;
                    result=2192818 - exp;
                    break;
                    case 82: cout << " What is your current experience? ";
                    cin >> exp;
                    result=2421087 - exp;
                    break;
                    case 83: cout << " What is your current experience? ";
                    cin >> exp;
                    result=2673114 - exp;
                    break;
                    case 84: cout << " What is your current experience? ";
                    cin >> exp;
                    result=2951373 - exp;
                    break;
                    case 85: cout << " What is your current experience? ";
                    cin >> exp;
                    result=3258594 - exp;
                    break;
                    case 86: cout << " What is your current experience? ";
                    cin >> exp;
                    result=3597792 - exp;
                    break;
                    case 87: cout << " What is your current experience? ";
                    cin >> exp;
                    result=3972294 - exp;
                    break;
                    case 88: cout << " What is your current experience? ";
                    cin >> exp;
                    result=4385776 - exp;
                    break;
                    case 89: cout << " What is your current experience? ";
                    cin >> exp;
                    result=4842295 - exp;
                    break;
                    case 90: cout << " What is your current experience? ";
                    cin >> exp;
                    result=5346332 - exp;
                    break;
                    case 91: cout << " What is your current experience? ";
                    cin >> exp;
                    result=5902831 - exp;
                    break;
                    case 92: cout << " What is your current experience? ";
                    cin >> exp;
                    result=6517253 - exp;
                    break;
                    case 93: cout << " What is your current experience? ";
                    cin >> exp;
                    result=7195629 - exp;
                    break;
                    case 94: cout << " What is your current experience? ";
                    cin >> exp;
                    result=7944614 - exp;
                    break;
                    case 95: cout << " What is your current experience? ";
                    cin >> exp;
                    result=8771558 - exp;
                    break;
                    case 96: cout << " What is your current experience? ";
                    cin >> exp;
                    result=9684577 - exp;
                    break;
                    case 97: cout << " What is your current experience? ";
                    cin >> exp;
                    result=10692629 - exp;
                    break;
                    case 98: cout << " What is your current experience? ";
                    cin >> exp;
                    result=11805606 - exp;
                    break;
                    case 99: cout << " What is your current experience? ";
                    cin >> exp;
                    result=13034431 - exp;
                    case 100: cout << " What is your current experience? " <<endl;
                    cin >> exp;
                    result=14391160 - exp;
                    break;
                    default: exit(0);
                    }
                    cout << " Experience Needed: " << result  << endl;
// Ores needed to be mined to acquire the level up.
                    cout << " Rune Essence: " << ceil(result/5.0) << endl;
                    cout << " Clay: " << ceil(result/5.0) << endl;
                    cout << " Copper: " << ceil(result/17.5) << endl;
                    cout << " Tin: " << ceil(result/17.5) << endl;
                    cout << " Bluerite: " << ceil(result/17.5) << endl;
                    cout << " Iron: " << ceil(result/35.0) << endl;
                    cout << " Silver: " << ceil(result/40.0) << endl;
                    cout << " Coal: " << ceil(result/50.0) << endl;
                    cout << " Gold: " << ceil(result/65.0) << endl;
                    cout << " Mithril: " << ceil(result/80.0) << endl;
                    cout << " Adamant: " << ceil(result/ 95.0) << endl;
                    cout << " Runite: " << ceil(result/125.0) << endl;
                    cout << endl << endl << endl << "\t\t\tCreated by USDblades" << endl;
         return 0;
}

Edit: Sorry was not clear. I am trying to improve the code for the Runescape Skill Calculator I am working on. I am curious if I could have cut out some lines of code by using different functions. The Code provided is my project I am working on. Can you review it and give me pointers?

There is hardly a way without reading anything.

Language reference: http://www.cplusplus.com/doc/tutorial/

Bible: http://www.amazon.com/C-Programming-Language-Special/dp/0201700735/ref=pd_sim_b_3

I like this one a lot but it's probably not the first step: http://www.amazon.com/Effective-Specific-Addison-Wesley-Professional-Computing/dp/0201924889

This is the unbelievable book but its content borders with insanity at some point :) http://www.amazon.com/Modern-Design-Generic-Programming-Patterns/dp/0201704315/ref=pd_sim_b_6

Does it make any sense to write code like this?

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

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

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

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

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

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

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

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

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

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

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

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

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

Here is another Stack Overflow post that demonstrates this.

Further reading if interested:

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

I am designing some classes for my project in C++ at the moment but I got a problem. I want to create a camera class which holds all the needed values (e.g. transformation matrices) but the function which renders the camera should be exchangeable. This sounds like a usual case for the strategy pattern. Thus I created an interface which defines the render-function and gave the the camera class a pointer to this interface. The problem is that the render function needs access to all the data in the camera class and therefore I gave this function a pointer to the camera class as a parameter. It looks like this:

#include "ICameraRender.h"

class Camera{
private:
    ICameraRender*      _cameraRender;

public:
    Camera();
    Camera(ICameraRender& cameraRender);
    ~Camera();

    void renderCamera(){  _cameraRender->render(this); }


    void setCameraRender(ICameraRender& cameraRender);
        /..../

};


class ICameraRender{
public:
    virtual ~ICameraRender(){

    }

    //Override me
    virtual void render(Camera* camera) = 0;
};

This doesn't seem to be an elegant solution due to the liability to an infity loop (calling camera->renderCamera() in the render-function in ICameraRender). Is there a better solution to this problem?

Regards

EDIT:

I came up with another solution. Since the function which operates on the camera's data, only needs access to the data I thought I could split up the camera class itself. A class called Camera and CameraModel. The last one holds all the needed data and the first one does operations on it. Therefore I just have to pass a pointer to CameraModel to my function:

class CameraModel{
private:
    /...data.../
public:
   /...setter and getter.../
};

class Camera{
private: 
    CameraModel*   _cameraModel;
    ICameraRender* _cameraRender;

public:
Camera();
    Camera(ICameraRender& cameraRender);
    ~Camera();

    void renderCamera(){  _cameraRender->render(_cameraModel); }

    void setCameraRender(ICameraRender& cameraRender);
        /..../
};

class ICameraRender{
public:
    virtual ~ICameraRender(){

    }

    //Override me
    virtual void render(CameraModel* cameraModel) = 0;
};

Now the render-function (which only calculates new values for the camera according to user input) does no longer have access to the renderCamera-function. What do you think about this solution?

Regards Stan

This is probably a great time to use Policy-based design to implement the strategy pattern, especially since you're using C++ and you're probably targeting a compiler older than 2002. (Since C++'s templating mechanism is so awesome, we can get the strategy pattern for free this way!)

First: Make your class accept the strategy/policy class (in this case, your ICameraRenderer) at a template parameter. Then, specify that you are using a certain method from that template parameter. Make calls to that method in the camera class...

Then implement your strategies as a plain old class with a render() method!

This will look something like this:

class Camera<RenderStrategy>{
    using RenderStrategy::render;

    /// bla bla bla 

    public:
        void renderCamera(){  render(cameraModel); }
};

class SpiffyRender{
    public:
        void render(CameraModel orWhateverTheParameterIs){ // some implementation goes somewhere }
};

Whenever you want to make a camera that uses one of those policy/strategies:

// the syntax will be a bit different, my C++ chops are rusty; 
// in general: you'll construct a camera object, passing in the strategy to the template  parameter
auto SpiffyCamera = new Camera<SpiffyRender>();

(Since your renderer strategy doesn't have any state, that makes this approach even more favorable)

If you are changing your renderer all the time, then this pattern / approach becomes less favorable... but if you have a camera that always renders the same way, this is a slightly nicer approach. If your renderer has state, you can still use this method; but you'll want a reference to the instance inside the class, and you won't use the Using:: statement. (In general, with this, you write less boilerplate, don't need to make any assignments or allocations at runtime, and the compiler works for you)

For more about this,see: http://en.wikipedia.org/wiki/Policy-based_design Or read Modern C++ Design... it's a great read, anyways! http://www.amazon.com/Modern-Design-Generic-Programming-Patterns/dp/0201704315

As an unrelated aside: You may want to look into some of the goodness that C++x11 gives you. It'll really clean up your code and make it safer. (Especially the shared/unique/etc ptr classes.)

I'm teaching myself c++ by creating my own data structure class (a matrix, to be exact) and I've changed it to a template class of type <T> from only using doubles. The overloaded matrix operators were pretty standard

    // A snippet of code from when this matrix wasn't a template class
    // Assignment
    Matrix& operator=( const Matrix& other );

    // Compound assignment
    Matrix& operator+=( const Matrix& other ); // matrix addition
    Matrix& operator-=( const Matrix& other ); // matrix subtracton
    Matrix& operator&=( const Matrix& other ); // elem by elem product
    Matrix& operator*=( const Matrix& other ); // matrix product

    // Binary, defined in terms of compound
    Matrix& operator+( const Matrix& other ) const; // matrix addition
    Matrix& operator-( const Matrix& other ) const; // matrix subtracton
    Matrix& operator&( const Matrix& other ) const; // elem by elem product
    Matrix& operator*( const Matrix& other ) const; // matrix product

    // examples of += and +, others similar
    Matrix& Matrix::operator+=( const Matrix& rhs )
    {
        for( unsigned int i = 0; i < getCols()*getRows(); i++ )
        {
            this->elements.at(i) += rhs.elements.at(i);
        }
        return *this;
    }

    Matrix& Matrix::operator+( const Matrix& rhs ) const
    {
        return Matrix(*this) += rhs;
    }

But now that Matrix can have a type, I'm having trouble determining which of the matrix references should be type <T> and what the consequences would be. Should I allow dissimilar types operate on each other (eg., Matrix<foo> a + Matrix<bar> b is valid)? I'm also a little fuzzy on how

One reason I'm interested in dissimilar types is to facilitate the use of complex numbers in the future. I'm a newbie at c++ but am happy to dive in over my head to learn. If you're familiar with any free online resources that deal with this problem I would find that most helpful.

Edit: no wonder no one thought this made sense all of my angle brackets in the body were treated as tags! I can't figure out how to escape them, so I'll inline code them.

I figure that I should illustrate my comment about parameterizing matrix dimensions, since you might not have seen this technique before.

template<class T, size_t NRows, size_t NCols>
class Matrix
{public:
    Matrix() {} // `data` gets its default constructor, which for simple types
                // like `float` means uninitialized, just like C.
    Matrix(const T& initialValue)
    {   // extra braces omitted for brevity.
        for(size_t i = 0; i < NRows; ++i)
            for(size_t j = 0; j < NCols; ++j)
                data[i][j] = initialValue;
    }
    template<class U>
    Matrix(const Matrix<U, NRows, NCols>& original)
    {
        for(size_t i = 0; i < NRows; ++i)
            for(size_t j = 0; j < NCols; ++j)
                data[i][j] = T(original.data[i][j]);
    }

private:
    T data[NRows][NCols];

public:
    // Matrix copy -- ONLY valid if dimensions match, else compile error.
    template<class U>
    const Matrix<T, NRows, NCols>& (const Matrix<U, NRows, NCols>& original)
    {
        for(size_t i = 0; i < NRows; ++i)
            for(size_t j = 0; j < NCols; ++j)
                data[i][j] = T(original.data[i][j]);
        return *this;
    }

    // Feel the magic: Matrix multiply only compiles if all dimensions
    // are correct.
    template<class U, size_t NOutCols>
    Matrix<T, NRows, NOutCols> Matrix::operator*(
        const Matrix<T, NCols, NOutCols>& rhs ) const
    {
        Matrix<T, NRows, NOutCols> result;
        for(size_t i = 0; i < NRows; ++i)
            for(size_t j = 0; j < NOutCols; ++j)
            {
                T x = data[i][0] * T(original.data[0][j]);
                for(size_t k = 1; k < NCols; ++k)
                    x += data[i][k] * T(original.data[k][j]);
                result[i][j] = x;
            }
        return result;
    }

};

So you'd declare a 2x4 matrix of floats, initialized to 1.0, as:

Matrix<float, 2, 4> testArray(1.0);

Note that there is no requirement for the storage to be on the heap (i.e. using operator new) since the size is fixed. You could allocate this on the stack.

You can create another couple matrices of ints:

Matrix<int, 2, 4> testArrayIntA(2);
Matrix<int, 4, 2> testArrayIntB(100);

For copying, dimensions must match though types do not:

Matrix<float, 2, 4> testArray2(testArrayIntA); // works
Matrix<float, 2, 4> testArray3(testArrayIntB); // compile error
// No implementation for mismatched dimensions.

testArray = testArrayIntA; // works
testArray = testArrayIntB; // compile error, same reason

Multiplication must have the right dimensions:

Matrix<float, 2, 2> testArrayMult(testArray * testArrayIntB); // works
Matrix<float, 4, 4> testArrayMult2(testArray * testArrayIntB); // compile error
Matrix<float, 4, 4> testArrayMult2(testArrayIntB * testArray); // works

Note that, if there's a botch, it is caught at compile time. This is only possible if the matrix dimensions are fixed at compile time, though. Also note that this bounds checking results in no additional runtime code. It's the same code that you'd get if you just made the dimensions constant.

Resizing

If you don't know your matrix dimensions at compile time, but must wait until runtime, this code may not be of much use. You'll have to write a class that internally stores the dimensions and a pointer to the actual data, and it will need to do everything at runtime. Hint: write your operator [] to treat the matrix as a reshaped 1xN or Nx1 vector, and use operator () to perform multiple-index accesses. This is because operator [] can only take one parameter, but operator () has no such limit. It's easy to shoot yourself in the foot (force the optimizer to give up, at least) by trying to support a M[x][y] syntax.

That said, if there's some kind of standard matrix resizing that you do to resize one Matrix into another, given that all dimensions are known at compile time, then you could write a function to do the resize. For example, this template function will reshape any Matrix into a column vector:

template<class T, size_t NRows, size_t NCols>
Matrix<T, NRows * NCols, 1> column_vector(const Matrix<T, NRows, NCols>& original)
{   Matrix<T, NRows * NCols, 1> result;

    for(size_t i = 0; i < NRows; ++i)
        for(size_t j = 0; j < NCols; ++j)
            result.data[i * NCols + j][0] = original.data[i][j];

    // Or use the following if you want to be sure things are really optimized.
    /*for(size_t i = 0; i < NRows * NCols; ++i)
        static_cast<T*>(result.data)[i] = static_cast<T*>(original.data)[i];
    */
    // (It could be reinterpret_cast instead of static_cast. I haven't tested
    // this. Note that the optimizer may be smart enough to generate the same
    // code for both versions. Test yours to be sure; if they generate the
    // same code, prefer the more legible earlier version.)

    return result;
}

... well, I think that's a column vector, anyway. Hope it's obvious how to fix it if not. Anyway, the optimizer will see that you're returning result and remove the extra copy operations, basically constructing the result right where the caller wants to see it.

Compile-Time Dimension Sanity Check

Say we want the compiler to stop if a dimension is 0 (normally resulting in an empty Matrix). There's a trick I've heard called "Compile-Time Assertion" which uses template specialization and is declared as:

template<bool Test> struct compiler_assert;
template<> struct compiler_assert<true> {};

What this does is let you write code such as:

private:
    static const compiler_assert<(NRows > 0)> test_row_count;
    static const compiler_assert<(NCols > 0)> test_col_count;

The basic idea is that, if the condition is true, the template turns into an empty struct that nobody uses and gets silently discarded. But if it's false, the compiler can't find a definition for struct compiler_assert<false> (just a declaration, which isn't enough) and errors out.

Better is Andrei Alexandrescu's version (from his book), which lets you use the declared name of the assertion object as an impromptu error message:

template<bool> struct CompileTimeChecker
{ CompileTimeChecker(...); };
template<> struct CompileTimeChecker<false> {};
#define STATIC_CHECK(expr, msg) { class ERROR_##msg {}; \
    (void)sizeof(CompileTimeChecker<(expr)>(ERROR_##msg())); }

What you fill in for msg has to be a valid identifier (letters, numbers, and underscores only), but that's no big deal. Then we just replace the default constructor with:

Matrix()
{   // `data` gets its default constructor, which for simple types
    // like `float` means uninitialized, just like C.
    STATIC_CHECK(NRows > 0, NRows_Is_Zero);
    STATIC_CHECK(NCols > 0, NCols_Is_Zero);
}

And voila, the compiler stops if we mistakenly set one of the dimensions to 0. For how it works, see page 25 of Andrei's book. Note that in the true case, the generated code gets discarded so long as the test has no side effects, so there's no bloat.

I want something like this:

class TestParent<class T>
{
    T* some();
}

class TestChild : public TestParent<TestChild>
{};

Is this possible?

Thanks.

This is possible but only if you define an implementation of some otherwise you'll be confronted by compilation errors. You may also want to add a protected constructor so that your base class can't be created and used outside of how you define it in your header scope.

template<typename T>
class TestParent{
    public:

        T* some() { return new T(); }

    //this is suggested
    protected:
        TestParent(){}
};

class TestChild : public TestParent<TestChild>{}

This is used in the curiously recuring template pattern and other techniques from policy-based design made popular by Alexandrescu's book.

Let me start with a concrete example. In C++, I have a hierarchy of classes under the abstract base class CollisionVolume. Any collision volume needs to be able to detectCollision with any other volume. This collision code is specialized based on the two subclasses in presence, but it is commutative: detectCollision(a, b) == detectCollision(b, a).

I need to use a mechanism similar to virtual functions since the objects will typically be of the abstract base class. However, if I use typical virtual methods, the chosen function can only depend on the type of one of the operand, not both. The only way I was able to do this is using RTTI or an RTTI-like mechanism.

Is there any cleaner way to do this?

There are several solutions to emulate multimethods in C++.

Here some references that can helps you to solve your problem:

S.Meyers "More effective C++", Item 31: Making functions virtual with respect to more than one object.

A.Alexandrescu "Modern C++ design", Chapter 11. Multimethods

MultiMethods in C++: Finding a complete solution by Danil Shopyrin

Multiple Dispatch. A new approach using templates and RTTI by Dr. Carlo Pescio, C++ Report, June 1998.

Draft proposal for adding Multimethods to C++, here and here

how to answer this question?

Andrei Alexandrescu talks about this briefly in Modern C++ Design.

He outlines two disadvantages to the monostate pattern:

  1. Static functions cannot be virtual.
  2. Initialization and cleanup is not central.

Number 1 means extending or changing the class might be made more difficult. Number 2 makes it difficult to track the life-time of data.

The monostate pattern and the singleton pattern solve two different but close problems. The monostate pattern makes sure all instances of the class operate on the same data, while a singleton makes sure here is only of instance of the class to operate with.

I am trying to refactor some code using policies (see the book Modern C++ Design) and want to shorten or simplify the code for the methods of the host classes. Let's say I have an already implemented class named Hostclass:

// Hostclass header, start version
struct Hostclass {
    void Hostfct1();
    void Hostfct2();
    ...
};
// method definitions, start version
void
Hostclass::Hostfct1(){...}

void
Hostclass::Hostfct2(){...}
...

Now I have a policy class

struct Policy1class {
    void Policy1fct(){};
};

and want to inject Policy1class into Hostclass. This means I have to change the Header of Hostclass:

// Hostclass header, second version
template <typename Policy1>
struct Hostclass : public Policy1 {

But what about the methods? Hostclass is now a template class, so the function definitons demand another specifier:

// method definitions, second version
template <typename Policy1>
void
Hostclass<Policy1>::Hostfct() {...}
...

Now I want to enrich Hostclass further with another policy

struct Policy2class {
    void Policy2fct(){};
};

so I have to change the header again:

// Hostclass header, third version
template <typename Policy1, typename Policy2>
struct Hostclass : public Policy1, Policy2 {

as well as the specifier:

// method definitions, third version
template <typename Policy1, typename Policy2>
void
Hostclass<Policy1,Policy2>::Hostfct() {...}
...

I think changing all specifiers of all hostclass methods everytime a new policy enters the stage is a bit a pain in the ass. Is it possible, perhaps with the new tools of C++14 and its template aliases or extern template, to simplify this method definition? I have something like this

// invalid code
class P1;
class P2;
using H = Hostclass<P1,P2>;
// method definitions, dream version
void
H::Hostfct1() {...}

void
H::Hostfct2() {...}
...

in mind. The only other option I could think of to circumvent the definition specifications is to implement a HostclassWrapper class which inherits itself from Hostclass and all other policies:

// Hostclass header, start version
struct Hostclass {...};
// method definitions, start version
void
Hostclass::Hostfct1(){...}
// new wrapper class
template <typename Policy1, typename Policy2>
class HostclassWrapper : public Hostclass, Policy1, Policy2 {
};

Any other suggestions?

You could simply use variadic templates:

template <class... Policies>
class Host : public Policies... { ... }

template <class... Policies>
void Host<Policies...>::func() { ... }

The only way around avoiding repeating the template declaration in each of the member function definitions would be to just define them all in the class definition itself.

But if you're supporting some arbitrary number of policies, a variadic template is definitely what you want.

I have a requirement for reading, updating and deleting a file. I want to write a class for this. For example

class FileManagement {
private:
    fstream myFile;

public:
    void read();
    void update();
    void delete();

};

My question is while updating is it possible to delete only one line in a file in C++ and should be portable, if it is possible how we can achieve this. Other question is if above option is not possible how we can achieve the above.

In C++ how we can delete a file in portable way.

Thanks!

If you are looking for a higher-level C++ library that is object-oriented and can handle both filename manipulation and file I/O, POCO is a decent choice:

http://pocoproject.org

ACE is an older, battle-tested framework that includes lots of I/O support. It's commonly used for it's excellent CORBA support, but there's a lot in there:

http://www.cs.wustl.edu/~schmidt/ACE-overview.html

And, finally, there's QT. Normally known for its cross-platform UI library, QT actually includes several other useful pieces (including file management and I/O), and you don't even have to link in the UI stuff if you don't need it.

http://qt.nokia.com/

If you'd rather not bring in another framework, I would recommend rolling your own File I/O classes using boost::filesystem and either the standard iostream or stdio functions. You can use the interfaces in the above frameworks as a reference, but you will also want to familiarize yourself with modern C++ design, as demonstrated by Boost and explained in Modern C++ Design.

I'm currently working on a little game, and I need somes class/struct to be allocated and deleted really often. I'm wondering it is a way to save deletion, maybe putting delete object in a container, and try to pick up in this container when i want to allocate an instance of the class.

I'm thinkin about overload of new and delete operator. But I have a little problem, if I overload the delete operator (to put the "deleted" object in the container), How delete it? Should I pass throught proper function to do that?

There are two ways you could go with that

1) A pool of objects. When you "allocate" you take an object from the pool and when you deallocate you return it back to the pool. This is not that transparent but the implementation is not that hard.

2) Create a custom allocator for your classes/structs. You preallocate the memory in a big buffer and when you need to allocate you take memory from there and when you need to deallocate you return the memory back (the actual mechanism is up to you). This is a bit harder to implement but can be more transparent.

Check the following links for ideas

Also, while you are at it, there is a great book by Alexandrescu

http://www.amazon.com/Modern-Design-Generic-Programming-Patterns/dp/0201704315

a bit old, but exceptional nevertheless and has a section for memory management/allocator.

I'm working on a large, old codebase that uses memory pools to great speed advantage. The problem, though, is that allocating and deallocating memory through the memory pool is complicated. I would like to try using smart pointers, but it was suggested to me that the loss in performance would be an issue.

The solution that seems to present itself is a smart pointer implementation that continues to use the original memory pool under the hood. I can't find any smart pointer/memory pool combinations in use. Can anyone point me to an example implementation of this? Are there any gotchas/cautions I should be aware of before trying this out?

Andrei Alexandrescu's Modern C++ Design has a good chapter on smart pointers. The Loki library described in the book provides templates that use policy classes to tune behavior of the smart pointers to your specific needs.

Be aware, these are a different beast than C++11's std::shared_ptr, and not compatible with those. Incorporating Loki into your codebase might not be a justifiable choice, depending on your maintenance needs. But the concepts in the book are worth exploring in any case.

My question is a bit about programming techniques or, maybe, design patterns. Suppose several classes derived from base which contains a pure virtual method that should do some interactions beetwen them.

For instance, Rectangle, Ellipse, Triangle and Line - all derived from a Shape. And this abstract class, Shape, contains virtual bool Intersects(Shape* another) = 0.

It seems, that I need to make six implementations, right (btw, is any better solution in this particular example?).

I have no idea of any other examples at the moment.

Maybe I'm talking about a thing that is well-known and I'm nearly sure there are some names describing the technique. However, I don't even know what to input to find it in the Internet.

Well, can you tell me how to implement such thing (I'm still wondering if any helper method is needed, or, maybe, RTII's dynamic_cast?) or point some sources (arts, tutorials or whatever) about it?

This is the school book example of double dispatch, the wikipedia article gives a good description of the problem and the solution:

http://en.wikipedia.org/wiki/Double_dispatch

If I remember correctly there's a very elegant solution to the problem in the book "Modern C++ Design" by Andrei Alexandescu

http://www.amazon.com/Modern-Design-Generic-Programming-Patterns/dp/0201704315

Say as an example I have a Player class that has a race via a Race class. These races are fixed in number and are loaded into an array which can be accessed statically.

My question is whether the Player class should have an index ID number which would then need to call the static function getRaceByID(int) to retrieve the Race class to do some internal calculations. Now I could get around having to do this if I was to have the race reference directly in the Player class, but then saving the player to a file becomes problematic. I only want a reference to the Race be stored along with the Player data. Like an ID.

I want to avoid storing a copy of the Race data and instead just reference it. Is there anything I should be doing differently? Are there any patterns to address something like this? Databases deal with IDs, but it doesn't seem to work very well in OO development. Any help is appreciated, thanks.


class Player
{
  Race race;
}

In this case I would need to compare this race to the races in my static array so that I can properly write out the index ID. Another solution is to store the ID in the Race class itself so that I can reference it directly from the Race class like so:

race.getID();

Or would it be better to go with something like this to enforce this relationship:

class Player
{
  int raceID;
}

Race r = MyFile.getRaceByID(raceID);

// can now use race

Of some relevance to using IDs in an OO design: Modern C++ Design by Alexandrescu has an excellent chapter on object factories. If you have a big switch statement on your ID, then you could probably benefit from reading this chapter, as it will show you the OO way to handle that sort of thing. As the book says:

The Shape-Drawing example [of polymorphism] is often encountered in C++ books, including Bjarne Stroustrup's classic (Stroustrup 1997). However, most introductory C++ books stop when it comes to loading graphics from a file, exactly because the nice model of having separate drawing objects breaks.... A straightforward implementation is to require each Shape-derived object to save an integral identifier at the very beginning. Each object should have its own unique ID. Then reading a file would look like this:

[code with big switch]

.... The only problem [with this type of code] is that it breaks the most important rules of object orientation: [E.G.,] It collects in a single source file knowledge about all Shape-derived classes in the program....

So I want to access a singleton class from multiple threads. Conceptually I'd think that calling non-const methods on this singleton instance would be not thread-safe. I've been looking online and no one seems to address this possible issue. Is there an actual problem with this, is the only issue with Singleton's thread-safety, the initialization of the instance variable?

A singleton instance has the same thread safety issues as any other instance, so calls to its methods or access to its members should be synchronized.

The initialization of the singleton itself is another issue...in gcc static initialization is threadsafe, but probably not so much on other platforms.

Also take a look at this paper addressing some threading singleton issues by Andrei Alexandrescu. His Modern C++ Design book also addresses singleton issues.

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 .

This question is extension of the question I want to understand how the elements are inserted into the STL Container.

Suppose I have A object;, which I want to insert into any of the STL Container, I understand that there is concept of allocators which handles the memory. But I fail to understand that how the actual object is copied into STL memory. So my object is stored on the stack when I call Container.insert how does STL create copy of this object and stored this objects into its memory.

Any equivalent C++ code would be helpful which simulates the same.

what really happens in terms of memory allocation is this: _it uses the allocator passed in as the allocator template parameter.

 map<int , long , less<int> , myAllocator<pair<int, long> > > myMap;

whatever you make myAllocator do it's allocations from (if any) will be used. This technically means that you could preallocate all the pairs (perhaps from a vector). It also implicates that placement new is being used, just like in the vector case, only that, instead of a single contiguous allocation, your allocation will be called many times for small allocations.

This only leads to the situation where the container cannot guarantee that storage is contiguous (like in the vector case), however, it miht still happen to be contiguous due to the implementation of your allocator

Writing allocators is an advanced topic and it has been addressed in

  • Modern C++ Design (A.Alexandrescu)
  • Boost library
  • See also EASTL (which is designed for (embedded) game programming; In such environments, a heap is often 'non-existant' or prohibited; Moreover, performance is of the utmost importance in this area. EASTL doesn't come with a default allocator.)
    https://github.com/paulhodge/EASTL

What are the elegant design pattern(GoF patterns) implementation in c++ ?

Can anyone give me some examples of design pattern implementations based on template(which can be reused) ?

Example(Template based Singleton) :-

template<typename T>
class Singleton : public boost::noncopyable
{
public:
    static Singleton& GetInstance()
    {
        boost::call_once(&CreateInstance, m_onceFlg);
        return *m_pInstance;
    }
    virtual ~Singleton()
    {
    }
protected:
    Singleton ()
    {
    }
    static void CreateInstance()
    {
        m_pInstance.reset(new T());
    }
private:
    static boost::once_flag m_onceFlg;
    static boost::scoped_ptr<T> m_pInstance;
};

Take a look at Modern C++ Design by Alexandrescu

http://www.amazon.com/Modern-Design-Generic-Programming-Patterns/dp/0201704315

He covers template implementation of several design patterns. In fact, IIRC, one of the forewards is written by one of the GOF.