Chapter 16

imageAdditional Library Utilities

WHAT’S IN THIS CHAPTER

  • How you can use std::function for function pointers
  • How to work with compile time rational numbers
  • How to work with time
  • How to generate random numbers
  • What tuples are and how to use them

C++11 adds a lot more functionality to the C++ standard library not described in previous chapters. These additional library features are combined and explained in this chapter because they don’t fit anywhere else.

STD::FUNCTION

std::function, defined in the <functional> header file, can be used to create a type that can point to a function, a function object, or a lambda expression; basically anything that is callable. It can be used as a function pointer or as a parameter for a function to implement callbacks. The template parameters for the std::function template look a bit different than most template parameters. Its syntax is as follows:

std::function<R(ArgTypes...)>

R is the return value type of the function and ArgTypes is a comma-separated list of argument types for the function.

The following example demonstrates how to use std::function to implement a function pointer. It creates a function pointer f1 to point to the function func(). Once f1 is defined, you can call func() by using the name func or f1:

image
void func(int num, ...

Get Professional C++, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.