cppannotations/yo/advancedtemplates/select.yo

42 lines
2.1 KiB
Text
Raw Normal View History

The inverse operation of determining the index of a certain type in a
tt(TypeList) is retrieving the type given its index. This inverse operation is
the topic of this section.
The algorithm is implemented using a struct tt(TypeAt). tt(TypeAt) uses a
tt(typedef) to define the type matching a given index. But the index might be
out of bounds. In that case we have several options:
itemization(
it() Use a link(static_assert)(STATICASSERT) to stop the compilation. This
is an appropriate action if the index should simply not be out of bounds;
it() Define a local type (e.g., tt(Null)) that should not be used as a
type in the tt(TypeList). Using that local type as a type in a tt(TypeList) is
considered an error as its use in a tt(TypeList) could easily cause confusion
(was the index invalid? did we actually stumble across tt(Null)?). A
tt(static_cast) may be used to prevent tt(Null) from being returned as the
type matching the search index;
it() The struct tt(TypeAt) may define a enum value tt(validIndex) set to
tt(true) if the index was valid and set to tt(false) if not.
)
The first alternative is implemented below. The other alternatives are not
difficult to implement and are left as exercises for the reader. Here's how
tt(TypeAt) works:
itemization(
it() The foundation consists of a variadic template struct tt(TypeAt),
expecting an index and a tt(TypeList):
verbinsert(TYPEAT)(examples/typeat.h)
it() If the typelist is empty a tt(static_assert) ends the compilation
verbinsert(INVALID)(examples/typeat.h)
it() If the search index equals 0, define tt(Type) as the first type in
the tt(TypeList):
verbinsert(ZERO)(examples/typeat.h)
it() Otherwise, tt(Type) is defined as tt(Type) defined by tt(TypeAt<index
- 1>) operating on the tt(TypeList)'s tail:
verbinsert(TYPELIST)(examples/typeat.h)
)
Here is how tt(typeAt) can be used. Uncommenting the first variable
definition causes a tt(TypeAt index out of bounds) compilation error:
verbinsert(EXAMPLE)(examples/typeat.cc)