Functional programming in C++11, F# style - c++

I've been looking at the new features in C++11 and it really looks like it will be possible to program in a very functional programming style using it. I've gotten use to using the types List, Seq, Array in F# and I see no reason why their members couldn't be ported into some sort of C++11 template. What problems or advantages do you see in using C++11 vs something like F# for a mixed functional programming style? Maybe the Boost guys will make a new functional once C++11 comes out.

The biggest problem with trying to program in a functional style in C++ is that it does not support tail recursion. In a functional language you don't have to worry about stack explosion when you tail recurse correctly, but in C++ you always have to worry about that. Therefore, many "functional" type algorithms will be clumsy or heavy.

Here are some of the problems I encountered trying to write functional code in C#, mixed with some goodies from my time when I was still using C++:
Lack of pattern matching. Once you get used to it, not having it can drive me crazy.
Lack of syntactic sugar for tuples.
Lack of syntax for copying records and setting fields in one go.
Lack of syntax for lists and arrays. That goes for constructors and pattern-matching.
Not having a GC, and unsafe memory accesses. Not being constrained by a GC is an advantage, but remembering the reports I got from my first runs of Valgrind on C++ code I thought was bug free scared me for ever.
Understanding template code isn't exactly accessible to all mortals. I don't have problem understanding mine, but whenever I looked into implementations of the STL, boost or cgal I found myself wondering what language they were using. My C++ and their C++ don't live in the same world.
The total lack of fun in dealing with a library that uses another version of boost (or any library that uses templates).
Verbosity of separate header/implementation files.
Type inference in C++ does not go as far as e.g. F#. I know it's been improved in C++11, but as I understand it's similar to var in C#, which isn't enough once you tasted F#-style inference.
Lack of computation expressions, including sequence expressions, comprehensions, async...
It would not surprise me if several of these points were actually possible in C++ using some template and preprocessor magic, but you can't really use these in a production environment unless you have very adventurous and tolerant co-workers.
I was a die-hard C++ enthusiast before. Then I started using generic programming with templates and higher-order functions using function objects. It just was too tiresome to write. After I tried a functional language I never looked back.

You might find this interesting:
http://smellegantcode.wordpress.com/2009/01/26/linq-to-c0x/

What problems of advantages do you see in using c++0x vs something like f# for a mixed functional programming style?
The upward funarg problem, which was debated in the context of Lisp 40 years ago!

I imagine that it would be… interesting… to implement certain optimizations common to functional languages in C++0x (like common subexpression elimination).

Related

What Language Features Can Be Added To Clojure Through Libraries?

For example pattern matching is a programming language feature that can be added to the clojure language through macros: http://www.brool.com/index.php/pattern-matching-in-clojure
What other language features can be added to the language?
Off the top of my hat I have two examples, but I'm sure there are more.
Contracts programming: https://github.com/fogus/trammel
Declarative logic: https://github.com/jduey/mini-kanren
I think its a stupid question to ask what can be added, what you should ask is what you cant add. Macros allow you to hook into the compiler that mean you can do almost anything.
At the moment you cant add your own syntax to the language. Clojure does not have a user extenseble reader, this means you don't have any reader-macros (http://dorophone.blogspot.com/2008/03/common-lisp-reader-macros-simple.html). This is not because of a technical problem but more a decition by Rich Hickey (the Clojure creator).
What you can not do is implement features that need virtual maschine support like add tail call semantics or goto.
If you want to see some stuff that has been done: Are there any Clojure DSLs?
Note that this list is not 100% up to date.
Edit:
Since you seem you took pattern matching as an example (it is a really good example for the power of macros) you should really look at the match library. Its probebly the best fastest pattern matching library in Clojure. http://vimeo.com/27860102
You can effectively add any language features you like.
This follows from the ability of macros to construct arbitrary code at compile time: as long as you can figure out what code you need to generate in order to implement your language features, it can be achieved with macros.
Some examples I've seen:
Query languages (Korma)
Logic programming (core.logic)
Image synthesis DSL (clisk)
Infix notation for arithmetic
Algebraic manipulation
Declarative definition of realtime data flows (Storm, Aleph)
Music programming (Overtone, Music As Data)
There are a few caveats:
If the feature isn't supported directly by the JVM (e.g. tail call optimisation in the mutually recursive case) then you'll have to emulate it. Not a big deal, but may have some performance impact.
If the feature requires a syntax not supported by the Clojure reader, you'll need to provide your own reader (since Clojure lacks an extensible reader at present). As a result, it's much easier if you stick to Clojure syntax/forms.
If you do anything too unusual / unidiomatic, it probably won't get picked up by others. There is a lot of value in sticking to standard Clojure conventions.
Beware of using macros where they are not needed. Often, just using normal functions (perhaps higher order functions) is sufficient to implement many new language features. The general rule is: "don't use macros unless you absolutely need to".

What's the best way to move on to advanced C++?

And what's your suggestion to move to the next level of C++ programming for someone who may be called, well, an intermediate C++ programmer?
Intermediate Programmer: Understands ISO C++ reasonably well, can read and modify other's code with some luck, good with data structures and algorithms but not great
Learn C++0x
Learn what kind of assembly code gets generated for different construct types, maybe for x86
Forget language nuances and get the fundamentals -- automata theory from somewhere like Sipser or Papadimitriou
If you know OOP or at least think you do, consider how to incorporate functional programming skills with C++
Work on something on the lines of a compiler and open-source like LLVM or GNU Toolchain
The whole idea is busted -- the next level means more sophisticated data structures. So if you know AVL, consider learning left leaning red black trees et al
Now obviously nobody can do everything in this list without prioritizing, so we need some suggestion on what might be the best way forward.
NOTE: Thank you all for the very helpful responses.
I'd say you can do everything on the list, just not all at once. At least IMO, you're looking at things a bit backwards though. Learning C++ (or any other language) is a means to an end, not an end in itself.
Learning more advanced language techniques, more advanced data structures, etc., should mostly be done when and as needed to accomplish something. You certainly need a reasonable starting "base" to do much, but beyond a fairly small set of basics, most advanced techniques, data structures, etc., are also relatively specialized.
Instead of trying to learn something for it's own sake, write some code. When something seems clumsy, unnecessarily difficult, inflexible, etc., find a better way to handle it. This way, you'll not only learn the more advanced technique, data structure, etc., but also a good idea of what it really accomplishes so you'll have a decent idea of when, how, and why to use it (and just about as importantly, at least some idea of its limitations and when it's probably not applicable or useful).
To answer your specific questions:
Learn C++0x
You definitely need to do this. So possibly you have your answer right there...
Learn what kind of assembly code gets generated for different construct
types, maybe for x86
I would say learn how to understand the assembly language the compiler generates, in outline if not in detail. You certainly should not be trying to predict what the compiler will do, however.
Forget language nuances and get the fundamentals -- automata theory from
somewhere like Sipser or Papadimitriou
If it turns you on, I suppose...
If you know OOP or at least think you do, consider how to incorporate
functional programming skills with C++
Of all of the paradigms C++ supports, functional programming is probably the worst supported - if you want to learn FP, learn Haskell (or whatever), not C++.
Work on something on the lines of a compiler and open-source like LLVM or
GNU Toolchain
GNU is written in C, so it's not likely to boost your C++ skills - I know little about LLVM.
The whole idea is busted -- the next level means more sophisticated
data structures. So if you know AVL,
consider learning left leaning red
black trees et al
RB trees are not much more sophisticated than AVL trees - same basic concept. If you understand the basic structures covered in a data structures textbook, I don't see the need to dig further, unless the subject particularly interests you.
I'd learn about BOOST.
You can start piecemeal, just by using it, and as you get deeper into the libraries, you will find yourself thinking "How does that work?".
Using it will make you a more
productive and better C++ programmer!
Understanding how it works will get
you a "guru" badge!!
Contributing to and extending it will
ensure immortality!!!
If you know the basic language:
Then in this sort of order (though there will be some back tracking)
Learn study and digest RAII
Figure out how to use RAII in all C contexts so you are never stuck with C code.
Figure out Exceptions and what the exception guarantees are.
Figure out how to implement methods so that each of the different types of guarantees holds.
Learn about the standard containers.
Learn about the requirements required of each container.
Learn about iterators
Learn about iterator traits and how they work in conjunction with pointers.
Learn about the algorithms library
Learn about the stream library
Go back and learn how streams and iterators work
Learn about the method pointers and how they can be used in algorithms
Figure out what a functor is and how to use it.
Learn about bind and look at boost bind
Learn about the boost containers and how they differ from the standard containers.
Learn about smart pointers.
What are the different types and when to use each one effectively.
Start reading about the other things available in boost.
At this point you will be at the start of learning how to use C++
Learning assembly (e.g. to write assembly) might be a good idea, but I strongly suggest you don't become attached to the particulars of what your compiler generates, as that will change from version to version and optimization level to optimization level.
I would be a strong proponent of #4. Learning functional programming is very valuable. I haven't done a whole lot of it in C++, so I don't know how natural a fit it is, but I love how Ruby and Scala do functional programming.
I suggest you go into the designing part of programming. Learn how to design, write good code, learn good programming practices. Design patterns, UML, unit tests belong here.
As one hardly does the same thing all the time I also recommend, as you said, the assembly language. Learning assembly is fun and it really makes you understand computers better. Nothing beats the feeling of knowing how computers work at the lowest level.
Having knowledge of both low and high level programming beats everything else.
Don't worry too much about C++0x right now... make sure you really really really understand the basics first. This means make sure you understand references, pointers, L-values, R-values, templates, inheritance, memory management, etc etc. I'm not just saying grab a basic understanding of these, I'm saying really know the C++ memory model and what each expression means.
I really like #4 and #6. In regards to #6, try coding up some really advanced data structs in C++. Nothing will make you learn the language faster then trying to solve some problems that advanced data structs entail.
I'd say the next step is to read Structure and Interpretation of Computer Programs from cover to cover and do the exercises.
Study how other people solve difficult problems in an elegant way. Very important: just practice, without forgetting to evaluate. Have your code or problem solving methods reviewed.
Yes (referring to point 4), learn other programming languages, especially those that have specific advantages over c++, rather than applying their techniques directly in C++. Focus on finding methods for yourself to code with as few errors disrupting your workflow as possible, find a calibrated systematic and abstract approach that you can always apply to problem solving and implementation.
Collect/build a set of tools/libraries and coding practices that allow you to stop inventing the wheel, but deal with all the most common tasks in the best ways. Cause if you think about it, appart from bugs, readability, scalability and extensibility and in much lesser degree performance, if you write code that gets the job done, you have actually shown yourself a good programmer.
I aim at productivity here. If you are more into theory, you might as well just occupy yourself with little snippets and obscure language features.
For another point of view: 7. Learn other programming languages, as different from C++ as is practical. Definitely learn about functional programming, and don't worry about how it applies to C++ yet. Some languages to consider: Scheme, Common Lisp, Haskell, Prolog, Forth, Smalltalk. You don't have to become proficient in them, but you should try to understand how they work and what's good code in those languages.
If all you know is one language, your thinking will be restricted to what's natural in that language. If you know more than one, you'll be able to think in more different ways. You'll be more flexible in your approach to problems.
Anything you mentioned above will make you become a better C++ programmer. You need to make a choice based on your career plan. For example, if you want to develop hardware driver with C++, you should learn assembly code generated.

Is it Bad Practice to use C++ only for the STL containers?

First a little background ...
In what follows, I use C,C++ and Java for coding (general) algorithms, not gui's and fancy program's with interfaces, but simple command line algorithms and libraries.
I started out learning about programming in Java. I got pretty good with Java and I learned to use the Java containers a lot as they tend to reduce complexity of book keeping while guaranteeing great performance. I intermittently used C++, but I was definitely not as good with it as with Java and it felt cumbersome. I did not know C++ enough to work in it without having to look up every single function and so I quickly reverted back to sticking to Java as much as possible.
I then made a sudden transition into cracking and hacking in assembly language, because I felt I was concentrated too much attention on a much too high level language and I needed more experience with how a CPU interacts with memory and whats really going on with the 1's and 0's. I have to admit this was one of the most educational and fun experiences I've had with computers to date.
For obviously reasons, I could not use assembly language to code on a daily basis, it was mostly reserved for fun diversions. After learning more about the computer through this experience I then realized that C++ is so much closer to the "level of 1's and 0's" than Java was, but I still felt it to be incredibly obtuse, like a swiss army knife with far too many gizmos to do any one task with elegance. I decided to give plain vanilla C a try, and I quickly fell in love. It was a happy medium between simplicity and enough "micromanagent" to not abstract what is really going on. However, I did miss one thing about Java: the containers. In particular, a simple container (like the stl vector) that expands dynamically in size is incredibly useful, but quite a pain to have to implement in C every time. Hence my code currently looks like almost entirely C with containers from C++ thrown in, the only feature I use from C++.
I'd like to know if its consider okay in practice to use just one feature of C++, and ignore the rest in favor of C type code?
The short answer is, "This is not really the most effective way to use C++."
When used correctly, the strong type system, the ability to pass by reference, and idioms like RAII make C++ programs more likely to be correct, readable, and maintainable.
No one can stop you from using the language the way you want to. But you may be limiting yourself by not learning and leveraging actual C++ features.
If you write code that other people will have to read and maintain, they will probably appreciate the use of "real C++" instead of "C with classes" (in the words of a previous commenter).
Seems fine to me. That's the only part of C++ that I really use as well.
Right now, I'm writing a number cruncher. There's no polymorphism, no control delegation, no interaction. <iostream> was a bottleneck so I rewrote I/O in C.
The functions are mostly inside one class which represents a work thread. So that's not so much OO as having thread-local variables.
As well as vector, I use <algorithms> pretty heavily. But the heavy-duty data structures are written in plain C. Mainly circular singly-linked lists, which can't even easily have distinct begin() and end(), meaning not only containers but sequences (and for-loops) are off-limits. And then templates help the preprocessor to generate the main inner loop.
The most natural way of solving your problem is probably right. You don't want solutions in search of a problem. Learning to use C++ is well and good, but object orientation is suited to some problems and not others.
On the other hand, using bsearch from stdlib.h in a C++ program would be wrong.
You should use C++ in whatever way makes the most sense for you.

C++11: a new language?

Recently I started reading (just a bit) the current draft for the future C++11 standard.
There are lots of new features, some of them already available via Boost Libs. Of course, I'm pretty happy with this new standard and I'd like to play with all the new features as soon as possibile.
Anyway, speaking about this draft with some friends, long-time C++ devs, some worries emerged. So, I ask you (to answer them):
1) The language itself
This update is huge, maybe too huge for a single standard update. Huge for the compiler vendors (even if most of them already started implementing some features) but also for the end-users.
In particular, a friend of mine told me "this is a sort of new language".
Can we consider it a brand new language after this update?
Do you plan to switch to the new standard or keep up with the "old" standard(s)?
2) Knowledge of the language
How the learning curve will be impacted by the new standard?
Teaching the language will be more difficult?
Some features, while pretty awesome, seem a bit too "academic" to me (as definition I mean). Am I wrong?
Mastering all these new additions could be a nightmare, couldn't it?
In short, no, we can't consider this a new language. It's the same language, new features. But instead of being bolted on by using the Boost libs, they're now going to be standard inclusions if you're using a compiler that supports the 0x standard.
One doesn't have to use the new standard while using a compiler that supports the new standard. One will have to learn and use the new standard if certain constraints exist on the software being developed, however, but that's a constraint with any software endeavor. I think that the new features that the 0x standard brings will make doing certain things easier and less error prone, so it's to one's advantage to learn what the new features are, and how they will improve their design strategy for future work. One will also have to learn it so that when working on software developed with it, they will understand what's going on and not make large boo-boos.
As to whether I will "switch to the new standard", if that means that I will learn the new standard and use it where applicable and where it increases my productivity, then yes, I certainly plan to switch. However, if this means that I will limit myself to only working with the new features of the 0x standard, then no, since much of my work involves code written before the standard and it would be a colossal undertaking to redesign everything to use the new features. Not only that, but it may introduce new bugs and performance issues that I'm not aware of without experience.
Learning C++ has always been one of the more challenging journeys a programmer can undertake. Adding new features to the language will not change the difficulty of learning its syntax and how to use it effectively, but the approach will change. People will still learn about pointers and how they work, but they'll also learn about smart pointers and how they're managed. In some cases, people will learn things differently than before. For example, people will still need to learn how to initialize things, but now they'll learn about Uniform Initialization and Initializer Lists as primary ways to do things. In some cases, perhaps understanding things will be easier with the addition of the new for syntax for ranges or the auto return type in a function declaration. I think that overall, C++ will become easier to learn and use while at the same time becoming easier to teach.
Mastering a language is a long-term goal, it can not be done over night. It's silly to think that one can have mastery over something as complex as C++ quickly. It takes practice, experience and debugging code to really hammer something in. Academically learning is one thing, but putting to use that knowledge is an entire different monster. I think that if one already has mastery of the C++ language, the new concepts will not pose too much of a burden, but a new comer may have an advantage in that they won't bother learning some of the more obsolete ways of doing things.
1) The language itself
As far as I'm aware, there are really no breaking changes between
C++'03 and C++'0x. The only one I can think of here relates to using
auto as a storage class specifier, but since it had no semantic
meaning I don't see that being an issue.
There are a lot of other academic fixes to the standard which are very
necssary, for example better descriptions for the layout of member
data. Finally, with multi-core/cpu architectures becoming the norm,
fixing the memory model was a must.
2) Knowledge of the language
Personally, I feel that for 99.9% of C++ developers the newer language is going to be easier to use. I'm specifically thinking of features such as auto, lambda's and constexpr. These features really should make using the language more enjoyable.
At a more advanced level, you have other features such as variadic
templates etc that help the more advanced users.
But there's nothing new here, I'm still surprised at the amount of
everyday C++ developers that haven't used (or even heard of) the STL.
From a personal perspective, the only feature I'm a bit concerned about in the new standard is that of concepts. As it is such a large change, the same problems that occurred with templates (ie. completely broken implementations) is a real danger.
Update post FDIS going out for voting:
As it happens, 'concepts' was dropped for C++ 0x and will be taken up again for C++ 1x. In the end there are some changes other than auto which could break your code, but in practise they'll probably be pretty rare. The key differences can be found in Appendix C.2 of the FDIS (pdf).
For me, one of the most important, will be:
unique_ptr + std::move() !
Imagine:
Smart pointer without any overhead:
no reference counting operations
no additional storage for reference counter variable
Smart pointer that can be moved, ie. no destructor/constructor calls when moved
What does this give you? Exception safe, cheap (pointers..) containers without any costs. The container will be able to just memcpy() unique_ptrs, so there will be no performance loss caused by wrapping regular pointer by smart pointer! So, once again:
You can use pointers
It will be safe (no memory leaks)
It will cost you nothing
You will be able to store them in containers, and they will be able to do "massive" moves (memcpy-like) with them cheaply.
It will be exception safe
:)
Another point of view:
Actually, when you move group of objects using copy(), there is constructor and destructor call for every object instance. When you copy 1000 objects of 1kb size, there will be at least one memcpy() and 2000 function calls.
If you would want to avoid the thousands of calls, you would have to use pointers.
But pointers are: dangerous, etc. Actual smart pointers will not help you, they solve other problems.
There is no solution for now. You must pay for C++ RAII/pointer/valuevars design from time to time. But with C++0x, using unique_ptr will allow to do "massive" moves of objects (yes, practically objects, because pointer will be smart) without "massive" constructor/destructor calls, and without risk of using pointers! For me, this is really important.
It's like relaxing the RAII concept (because of using pointers) without loosing RAII benefits. Another aspect: pointer wrapped in unique_ptr() will behave in many aspects similar to java reference object variable. The difference is that unique_ptr() will be able to exist in only one scope at a time.
Your friend is partially right but mostly wrong: it's the same language with extra features.
The good thing is, you don't have to master all the new features. One of the primary mandates for a standards body is to not break existing code, so you'll be able to go on, happily coding in your old style (I'm still mostly a C coder even though I do "C++" applications :-).
Only when you want to have a look at the new features will you need to bone up on the changes. This is a process you can stretch over years if need be.
My advice is to learn what all the new features are at a high level (if only to sound knowledgeable in job interviews) but learn the details slowly.
In some respects, C++0x should be easier to teach/learn than current C++:
Looping through a container - the new for syntax is far easier than for_each + functor or looping manually using iterators
Initialising containers: we'll be able to initialise sequences with the same syntax as arrays
Memory management: out goes dodgy old auto_ptr, in comes well-defined unique_ptr and shared_ptr
Lambdas, although necessarily more complex than other languages' equivalents, will be easier to learn than the C++98 process of defining function objects in a different scope.
Do you plan to switch to the new standard or keep up with the "old" standard(s)?
A year ago, I was writing strict C89, because the product in question was aggressively portable to embedded platforms, some of which had compilers with radically different ideas of which bits of C99 it's worth supporting. So a 20-year-old standard still hasn't been fully replaced by its 10-year-old successor.
So I don't expect to be able to get away from C++03 any time soon.
I do expect to use C++0x features where appropriate. Just as I use C99 features in C code, and gcc extensions in C and C++ (and would use MSVC extensions, although I've never worked on MSVC-only code for more than trivial amounts of time). But I expect it to be "nice to have" rather than baseline, pretty much indefinitely.
You have a point, but it's always been the case. There is a lot of C++ code out there that still doesn't incorporate anything from the '98 standard just because of the innate conservatism of some coders. Some of us remember a dark time before the std:: namespace (before namespaces, in fact), when everyone wrote their own string class, and pointers walked around naked all the time. There is a reason why we talk about "modern C++ style" - to distinguish from the earlier style because some people still have to maintain or update code in that style.
Any language has to evolve to survive, and any language that evolves will have a divided user base, if only because people vary in their attitude towards estimating opportunity costs in applying new language features to their own work.
With the advent of C++0x in shipping compilers, this conversation will be played out over and over in dev teams across the world:
YOUNGSTER: I've just discovered these things called lambdas! And I'm finding lots of ways to use them to make our code more expressive! Look, I rewrote your old Foo class, isn't that much neater?
OLDSTER: There was nothing wrong with my old Foo class. You're just looking for excuses to use a "cool" new feature unnecessarily. Why do you keep trying to make my life so complicated? Why do I keep having to learn new things? We need another war, that's what we need.
YOUNGSTER: You're just too stuck in your ways, old man, we shouldn't even be using C++ these days... if it was up to me -
OLDSTER: If it was up to me we'd have stuck with PL/1, but no... my wife had to vote for Carter and now we're stuck with all this object-oriented crap. There's nothing you can do with std::transform and lambdas that I can't do with a goto and a couple of labels.
etc.
Your programming career will always involve learning and re-learning. You can't expect c++ to stay the same till you retire and to be using the same methods and practises that you were using 40 years ago. Technology rolls on, and it rolls quickly. It's your job to keep up with it. Of course you can ignore that, and continue to work the same way you currently do, but in 5 / 10 years time you'll become so outdated that you'll be forced to learn it all then when you're trying to change job. And it will have been a lot easier to learn on the job all those years before :)
A few months ago I heard Bjarne Stroustrup give a talk titled 50 years of C++. Admittedly, I'm not a C++ programmer, but it seemed to me that he certainly doesn't think 0x is a new language!
Whether or not we can consider it a "new language", I think that's semantics. It doesn't make a difference. It's backwards compatible with our current C++ code, and it's a better language. Whether or not we consider it "the same language" doesn't matter.
About learning the language, remember that a lot of the new features are there to make the language easier to learn and use. Most of the features that add complexity are intended for library developers only. They can use these new features to make better, more efficient, and easier to use libraries, that you can then use without knowing about the features. Several of the changes actually simplify and generalize existing features, making them easier for newcomers to learn.
It is a big update, yes, but it is guided by a decade of experience with the current C++ standard. Every change is there because experience has shown that it is needed. In fact, the committee is being extremely cautious and conservative, and have refused a huge number of other language improvements. What is added here is only the fundamentals that 1) everyone could agree on, and 2) could be specified in time, without delaying the new standard.
It is not simply a few language designers sitting down and brainstorming new features they'd like to try.
Concepts and Concept Maps are going to greatly increase the grokability of template frameworks. If you've ever poured over the Boost source you'll know what I mean. You're constantly going from source to docs because the language just doesn't have the facilities to express template concepts. Hopefully Concepts + Duck Typing will give us the best of both worlds whereby entry points to template libraries can explicitly declare requirements but still have the freedom that Duck Typing provides when writing generic code.
There are lots of good things in C++0x, but they're mostly evolutionary changes that refine or extend existing ideas. I don't think it's different enough to justify calling it a "new language".

What are the good and bad points of C++ templates? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
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:
C++ Templates: The Complete Guide by David Vandevoorde and Nicolai Josuttis (thorough introduction to the subject of templates)
Modern C++ Design. Generic Programming and Design Patterns Applied by Andrei Alexandrescu (what is the less known way of using templates to simplify your code, make development easier and result in code robust to changes)
C++ Template Metaprogramming by David Abrahms and Aleksey Gutov (again - different way of using the templates)
More C++ Idioms from Wikibooks presents some nice ideas.
On the positive side, C++ templates:
Allow for generalization of type
Decrease the amount of redundant code you need to type
Help to build type-safe code
Are evaluated at compile-time
Can increase performance (as an alternative to polymorphism)
Help to build very powerful libraries
On the negative side:
Can get complicated quickly if one isn't careful
Most compilers give cryptic error messages
It can be difficult to use/debug highly templated code
Have at least one syntactic quirk ( the >> operator can interfere with templates)
Help make C++ very difficult to parse
All in all, careful consideration should be used as to when to use templates.
My 2c are rather negative.
C++ types were never designed to perform compile time calculations.
The notion of using types to achieve computational goals is very
clearly a hack – and moreover, one that was never sought but rather
stumbled upon
..
The reward for using MP in your code is the moment of satisfaction of
having solved a hard riddle. You did stuff in 100 lines that would
have otherwise taken 200. You grinded your way through
incomprehensible error messages to get to a point where if you needed
to extend the code to a new case, you would know the exact 3-line
template function to overload. Your maintainers, of course, would have
to invest infinitely more to achieve the same.
Good points: powerful; allows you to:
prescribe compile-time attributes and computation
describe generic algorithms and datastructures
do many other things that would otherwise be repetitive, boring, and mistake-prone
does them in-language, without macros (which can be far more hazardous and obscure!)
Bad points: powerful; allows you to:
provoke compile-time errors that are verbose, misleading, and obscure (though not as obscure and misleading as macros...)
create obscure and hazardous misdesigns (though not as readily as macros...)
cause code bloat if you're not careful (just like macros!)
Templates vastly increase the viable design space, which is not necessarily a bad thing, but it does make them that much harder to use well. Template code needs maintainters who understand not just the language features, but the design consequences of the language features; practically speaking, this means many developer groups avoid all but the simplest and most institutionalized applications of C++ templates.
In general, templates make the language much more complicated (and difficult to implement correctly!). Templates were not intentionally designed to be Turing-complete, but they are anyway -- thus, even though they can do just about anything, using them may turn out to be more trouble than it's worth.
Templates should be used sparingly.
"Awful to debug" and "hard to read" aren't great arguments against good template uses with good abstractions.
Better negative arguments would go towards the fact that the STL has a lot of "gotchas", and using templates for purposes the STL already covers is reinventing the wheel. Templates also increase link time, which can be a concern for some projects, and have a lot of idiosyncrasies in their syntax that can be arcane to people.
But the positives with generic code reuse, type traits, reflection, smart pointers, and even metaprograms often outweigh the negatives. The thing you have to be sure of is that templates are always used carefully and sparingly. They're not the best solution in every case, and often not even the second or third best solution.
You need people with enough experience writing them that they can avoid all the pitfalls and have a good radar for when the templates will complicate things more than helping.
One of the disadvantages I haven't seen mentioned yet is the subtle semantic differences between regular classes and instantiations of class templates. I can think of:
typedefed typenames in ancestor types aren't inherited by template classes.
The need to sprinkle typename and template keywords in appropriate places.
Member function templates cannot be virtual.
These things can usually be overcome, but they're a pain.
Some people hate templates (I do) because:
On maintainability pov, the wrong use of templates can have a negative effect ten times stronger than the initial advantage of time they were supposed to bring.
On optimization pov, compiler optimizations they allow are nothing compared to an optimal algorithm and the use of multi threading.
On compiling time pov, wrong use of templates can a very negative effect on parsing, compilation and linking phases, when poorly written templated declaration brings tons of useless parasite declarations in each compilation units (here is how 200 lines of code can produce an .obj of 1Mb).
To me templates are like a chainsaw with an integrated flame thrower that can also launch grenades. One time in my life I may have a specific need of that. But most of the time, I'm using a regular hammer and a simple saw to build things and I'm doing a pretty good job that way.
Advantage: Generic Datatypes can be created.
Disadvantage: Code Bloating
I don't see how they are hard to read. What is unreadable about
vector <string> names;
for example? What would you replace it with?
Reusable code is made with template. Its application is in accordance with the profile of each.