timeline.FunktionalEng

Functional in C++98

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?

The overview

To get an overview of all functional features in classical, modern, and future C++ a timeline helps a lot.

timeline.FunktionalEng

The story of functional programming began with the first standard C++98. So, C++98 is the topic of this post.

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

Be part of my mentoring programs:

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (starts March 2024)
  • Do you want to stay informed: Subscribe.

     

    C++98

    timeline.Funktional98Eng

    Template metaprogramming

    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.

     TemplateInstanziierungEng

    The Factorial class template is the Hello World template metaprogramming, and it must not be missing in a post that mentions template metaprogramming.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    // factorial.cpp
    
    #include <iostream>
    
    template <int N>
    struct Factorial{
      static int const value= N * Factorial<N-1>::value;
    };
    
    template <>
      struct Factorial<1>{
      static int const value = 1;
    };
    
    int main(){
        
      std::cout << std::endl;
    
      std::cout << "Factorial<4>::value: " << Factorial<4>::value << std::endl;
      std::cout << "Factorial<5>::value: " << Factorial<5>::value << std::endl;
      
      std::cout << std::endl;
    
    }
    

     

    The program gives the expected result:

    factorial 

    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.

    factorialInstanziation

    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. 

    STL algorithm

    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.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    // algorithm.cpp
    
    #include <algorithm>
    #include <iostream>
    #include <numeric>
    #include <vector>
    
    int main(){
    
      std::cout << std::endl;
    
      std::vector<int> myVec{1,2,3,4,5,6,7,8,9};
    
      std::cout << "original:         ";
      for (auto a: myVec) { std::cout << a << " ";}
    
      std::cout << "\n\n";
      
      std::transform(myVec.begin(),myVec.end(),myVec.begin(), [](int i){ return i*i; });
    
      std::cout << "std::transform:   ";
      for (auto a: myVec) { std::cout << a << " ";}
      
      std::cout << "\n\n";
      
      myVec={1,2,3,4,5,6,7,8,9};
      
      auto logicalEnd= std::remove_if(myVec.begin(),myVec.end(), [](int i){ return !((i < 3) or (i > 8)); });
      myVec.erase(logicalEnd,myVec.end());
      
      std::cout << "std::remove_if:   ";
      for (auto a: myVec) { std::cout << a << " ";}
      
      std::cout << "\n\n";
      
      myVec={1,2,3,4,5,6,7,8,9};
      
      std::cout << "std::accumulate:  ";
      auto fak= std::accumulate(myVec.begin(),myVec.end(),1,[](int fir, int sec){ return fir * sec; });
      std::cout << "fak(10): " << fak << std::endl;
      
      std::cout << std::endl;
    
    }
    

     

    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. 

    algorithm

    What’s next?

    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

    Seminars

    I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

    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++
    • C++20

    Online Seminars (German)

    Contact Me

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *