S R T B H P N

FunctionObjects.h, FunctionObjects.cpp, FunctionObjects.txt, Code folder

Function objects are objects that can be invoked.
This demo illustrates the use of function pointers, functors, and lambdas.

#pragma once
/////////////////////////////////////////////////////////////////////////
// FunctionObjects.h - demonstrate function object declar and invoc.   //
//                                                                     //
// Jim Fawcett, CSE687 - Object Oriented Design, Summer 2017           //
/////////////////////////////////////////////////////////////////////////
/*
 * Function objects are functions, function pointers, functors, and
 * lambdas.  They are widely used in C++ code to:
 * - quickly define a locally useful function.
 * - start threads
 * - define callbacks
 * - define arguments for template functions, like STL algorithms
 */
#include <string>
#include <functional>

/*---------------------------------------------------------------------*/
/* Function declaration                                                */

void testFunction(size_t lineNo, const std::string& s);

/*---------------------------------------------------------------------*/
/*  Declaration of function pointer:                                   */
/*  fPtr can point to any function with the appropriate signature      */

void(*fPtr)(size_t lineNo, const std::string& s) = nullptr;

/*---------------------------------------------------------------------*/
/*  Declaration of a function pointer type                             */

typedef void(*FPtr)(size_t lineNo, const std::string& s); 

/*---------------------------------------------------------------------*/
/*  Declaration of an alias for an anonymous function pointer type     */

using AFPtr = void(*)(size_t lineNo, const std::string& s);

/*---------------------------------------------------------------------*/
/*  Declaration of a functor type                                      */
/*  The advantage of functors is that they can store data as           */
/*  instance members, used to pass to its operator() as arguments.     */

class FunctorExample
{
public:
  FunctorExample(size_t lineNo) : lineNo_(lineNo) {}
  void operator()(const std::string& arg);
private:
  size_t lineNo_;
};

/*---------------------------------------------------------------------*/
/*  Declares a standard function                                       */
/*  Standard functions can bind to any function object.                */ 
/*  We will bind to a lambda.  They are really just a shortcut         */
/*  for defining functors, as we show in main.                         */

std::function<void(const std::string& s)> stdFunc;