About
RSS

Bit Focus


How std::function is implemented [1/2]

This article is about how std::function is implemented and provide some implements that compiled in pre-C++11.

The std::function in C++11 is very fantastic as in a static compiling language like C++ it provides a set of interfaces to wrap any kind of callable objects. A more fantastic fact is that the only C++11 feature that std::function involves is variadic template.

So if we implements a simplified version of std::function with an arbitrary number of template parameters (say, 3 parameters, 1 for the return type and 2 for parameter types), it could be done in pre-C++11 so we don't have to learn the C++11 features right now.

Let us get down to the implements.

0. One pointer version

The std::function could be implemented as a class with only one pointer as its only data member, and of course several virtual functions.

The key point is to declare a virtual base class which could be used to wrap any kinds of callable object, like this.

Permanent Link: /p/4 Load full text

Post tags:

 C++

Traits in Generic Programming

Suppose we're going to construct a container, and need combining traits at the compile time. There are some ways to make it, for example, we may use several bools
template <bool AllowDuplicate, bool SortElements, bool CheckOutOfRange>
struct just_another_container;
To use that code will become some sort of nightmare, since every parameter is a bool, if you make a mistake on the order of arguments, you could hardly discover it before the program goes mad.
Another approach is, to merge all bools to a single unsigned, like
template <unsigned Policy>
struct just_another_container;
But that is not good too, since in the first place we have to define some flags
enum {
    ALLOW_DUP_MASK = 1,
    SORT_ELE_MASK = 2,
    CHECK_OUT_OF_RANGE_MASK = 4,
};
and then to use those flags, say, consider we add an insert interface to the container, which is concerned about whether or not allows duplicated elements in the container, the code may look like
void insert(element_type e)
{
    _insert<Policy & ALLOW_DUP_MASK>(e);
}

template <>
void _insert<0>(element_type e);

template <>
void _insert<ALLOW_DUP_MASK>(element_type e);
However unfortunately that won't compile, because C++ forbid specialize template functions (whether partial or not). So, we have to put that _insert into a template struct, like
template <unsigned AllowDuplicate>
struct insert_s
{
    static void insert(just_a_container& container, element_type& e);
};

template <>
struct insert_s<ALLOW_DUP_MASK>
{
    static void insert(just_a_container& container, element_type& e);
};

Permanent Link: /p/2 Load full text

Post tags:

 Generic Programming
 Template
 C++


. Back to Bit Focus
NijiPress - Copyright (C) Neuron Teckid @ Bit Focus
About this site