C++ is not a functional programming language, but you can program in a functional style. What are the functional features of C++? I will answer this question for C++98.
Specifically, I want to answer three questions in this and the following posts.
- Which functional features does C++ support?
- Which functional features do we get with C++17?
- What functional features can we hope for with C++20?
To get an overview of all functional features in classical, modern, and future C++ a timeline helps a lot.
The story of functional programming began with the first standard C++98. So, C++98 is the topic of this post.
Template Metaprogramming is programming with templates at compile time. Template instantiation generates the temporary source code that the compiler uses to generate the executable. The graphic shows this process for the class template Factorial.
The Factorial class template is the Hello World template metaprogramming, and it must not be missing in a post that mentions template metaprogramming.
The program gives the expected result:
Right, it’s not so thrilling that the program calculates the correct result. But it is thrilling what is happening under the hood.
Template metaprogramming is a pure functional programming language, which is turing complete. That means template metaprogramming is, in a strict sense a functional programming language (pure functional) and you can calculate all that is calculable (turing complete).
What is key for a pure functional programming language will be the topic of a future post. Only that much. Because of the template instantiation Factorial<5>::value in line 20, the class template (line 5 – 8) will be invoked and therefore, the class template Factorial<4>::value in line 7. This recursion ends with Factorial<0>::value. In this case the fully specialized class template in lines 10 – 13 kicks in.
To show it in a graphic, the template instantiation of Factorial<5>::value starts at compile time, a recursive process in such a way that the calculation result is already available at compile-time. From the perspective of the executable, it will make no difference if I use Factorial<5>::value or 120 in std::cout.
What are the functional characteristics of template metaprogramming, which you can observe in the class template Factorial.
Factorial has no state and no mutation and uses recursion. That should be enough for template metaprogramming.
What have the algorithm of the standard template library (STL) with functional programming in common? A lot. At first, one of its fathers Alexander Stephanov was a fan of functional programming; second, many of the algorithms of the STL are so-called higher-order functions. Higher-order functions are one of the key characteristics of functional programming.
Higher-order functions that can get functions as an argument or return functions.
In particular, the property that the STL algorithm can get functions as arguments are the main reason for the power of the STL. Examples? For simplicity reason, I use in the following lines the container and not ranges.
- std::transform modifies the elements of its container with the help of a function, which needs precisely one argument.
- std::remove_if remove all elements from the container fulfilling the property. A predicate defines the condition. A predicate is a function that returns a boolean.
- std::accumulate applies to all elements of the container a binary operation. The algorithm successively reduces the container to a final value.
Let’s have a look at the three functions in action.
I fully intentionally used lambda functions in the example. Although the algorithm can accept all, that behaves like a function. But lambda functions should be your first choice. C++ has supported lambda functions since C++11. That will also hold for the three additional features from C++11 that I used in the example: automatic type deduction with auto (lines 22, 32, and 39), unified initialization (lines 12, 26, and 36), and the range-based for-loop (line 22 and 32).
The program should be self-explanatory in combination with the output. I will only mention one specialty of the STL algorithm in line 28. The std::remove_if does not remove – like all generic algorithms of the STL – the elements from the container. std::remove_if returns the logical end of the new container. This logical end is used by the myVec.erase method, which shortens the container to its correct length.
The method erase is not a generic algorithm of the STL but a method of std::vector.
I will write in the next post about Technical Report 1 from 2005. I’m particularly interested in the two functions std::bind and std::function, which introduce a new technique in C++: partial function application. Partial function application is similar to the functional technique currying, also called schönfinkeln. Schönfinkeln, that sounds extremely promising.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, moon, and Philipp Lenk.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
|My special thanks to SHAVEDYAKS|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,