Function Objects using Variadic Templates in C++11

One of the biggest features introduced in C++11 are lambda expressions. Lamba expressions (or “lambdas”) are a powerful mechanism that allows defining functions “on-the-fly”. These can be stored in function objects and then be used by an object that doesn’t want to reveal its internal implementation, as well as to perform tasks on a parallel thread.

I was wondering how function objects could be implemented using other constructs of the language, mostly to see how much the language had to be changed in order to accomodate them. In this post I will show how to implement function objects using nothing but C++11’s variadic templates.

Variadic templates were introduced in our previous post in this C++11 series. This post will help pave the way for us to move into the more advanced topic of lambda expressions and std::function objects.

Function Pointers in C

As far as I can tell, C has always had functions as first-class citizens. Although their syntax is vastly different from the way one declares variables of other types, you could always define a variable that can be assigned a pointer to a function.

#include <stdio.h>
void print_number(int number)
{
    printf("Argument is: %d\n", number);
}

int main(int argc, char* argv[])
{
    void (*f)(int);  // f is a variable that can 
                     // store a pointer to a 
                     // function that receives 
                     // an int an returns nothing.
    f = print_number // legal.

    f(1024);         // calls print_number.  

    return 0;
}

Because C is a statically-typed language, we must be very careful with the types we declare f with, otherwise the assignment may be deemed invalid by the compiler.

Another problem is that the syntax can be cumbersome to remember and handle. Notice how the name of the variable is declared within the associated types.

Function Objects in C++

Unless you were using boost, C++ never had its own version of function objects until C++11. Programmers had to rely on the traditional C construct or write functors, classes that implement operator() and allow mimicking a function’s behavior.

Unlike C function pointers, functors are more readable, but we need to declare a class and implement operator() inside it. It’s much more verbose.

C++11 introduced the standard std::function type, which allows encapsulating a function declared by lamba expressions (or by other means). In production code, you will most certainly want to use std::functions. In this post, however, because of academic interest only, we’re going to exercise C++11’s variadic templates by implementing a generic function wrapper object called alg::function.

alg::function

Using variadic templates, it’s very easy to implement a simple function wrapper capable of handling any function type. I’m going to implement my solution using C function pointers. Remember: in C++11 production code, you will never do this.

namespace alg
{
    template <typename R, typename... T>
    class function
    {
        public:
            function(R (*f)(T...)) { _f = f; }
            R operator()(T... args) {return _f(args...);}
		
        private:
            R (*_f)(T...);

    };
}

And that’s all there is to it, really. Let’s go over the code.

I declare the class alg::function as a template that is to be instanciated by two parameters: a return type dubbed “R” and a list of types which I will refer to as “T”. The list of types can be empty, the return type is mandatory.

alg::function objects will have a single private member that is declared to be a pointer to a C function that returns a value of type R and receives the list of argument types T.

The only two additional methods that we need are: a public constructor that receives the function to wrap, storing it, and operator(), which will let us call the function. Notice how easily we can unpack the arguments when we call _f.

Instancing Examples

Let’s see it in action!

These samples illustrate the basic idea without complex data structures. It is certainly possible to pass alg::function objects around as the first-class citizens that they are, as well as passing-in and returning arbitrary C++ objects and structs from these wrappers.

The only limitation is the fact that we don’t support const parameters. Adding support for them would require tweaking the alg::function class a bit more. We leave this as an exercise to the reader.

A single function that receives an int and prints it:

void fun(int arg)
{
    std::cout << "hello from fun! (arg=" 
              << arg 
              << ")"
              << std::endl;
}

int main(int argc, char* argv[])
{
    alg::function<void, int> f(fun);

    f(0); // prints "hello from fun! (arg=0)"
}

A function that receives no parameters:

void fun2()
{
    std::cout << "hello from fun 2!" << std::endl;
}

int main(int argc, char* argv[])
{
    alg::function<void> f2(fun2);

    f2();  // prints "hello from fun 2!"
}

A function that receives two std::string instances and prints them together:

void fun4(std::string msg1, std::string msg2)
{
    std::cout << "hello from fun 4! (concat=" 
              << msg1 << msg2 
              << ")" 
              << std::endl;
}

int main(int argc, char* argv[])
{
    alg::function<void, std::string, std::string> f4(fun4);

    f4("hello, ", "world!"); // prints "hello from fun 4! (concat=hello, world!)"
}

Conclusion

Variadic templates offer a lot in terms of flexibility and allow us to extend the language even further than it was possible before. Remember, these examples are just food for thought. In C++11 production code, you will most certainly want to use std::function objects and lambda expressions.

See you next time!

Other articles in this C++11 series

2 thoughts on “Function Objects using Variadic Templates in C++11

  1. Hola Sego,

    Un truco para no no sufrir la sintaxis horrible para declarar punteros a funciĆ³n es usar un typedef intermedio:

    typedef void f_type(int);
    f_type* f = &print_number;

    Bruno

  2. Hola Bruno,

    Muchas gracias por el truco! Voy a intentar acordarme de esa sintaxis para el typedef.

    Ale.-

Comments are closed.