About

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

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
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(e);
}

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

template <>
void _insert(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
struct insert_s
{
    static void insert(just_a_container& container, element_type& e);
};

template <>
struct insert_s
{
    static void insert(just_a_container& container, element_type& e);
};
That looks really weird, and for struct insert_s, It should be granted public access to just_a_container.
Besides, in the code there would be full of bitwise-and here and there like

Permanent Link: /p/2/

Post tags:

C++

Generic Programming

Template

All 1

. Back to Tobary book
Tobary book - Copyright (C) ZhePlus @ Bit Focus
About