ToC
For example, the metafunction ContainerConcept#Iterator
is a type metafunction, i.e. it is used to determine a type. Type metafunctions have the form:
typename TypeMetaFunc<T1, T2, ..., TN>::Type
TypeMetaFunc
The name of the metafunction
T1, T2, ..., TN
Arguments (types or constants)
Type
The resulting type
The keyword typename
must be stated if one of the arguments T1, T2, ..., TN
is or uses a template parameter. For example the following piece of code uses the metafunction Iterator
to determine an iterator type for a string class:
demos/tutorial/metafunctions/base.cpp
demos/tutorial/metafunctions/base.cpp.stdout
Metafunctions can also be used to determine constant values at compile time. The general form of value metafunctions is:
VALUE_META_FUNC<T1, T2, ..., TN>::VALUE
VALUE_META_FUNC
The name of the metafunction
T1, T2, ..., TN
Arguments (types or constants)
VALUE
The resulting constant value
For example the following function prints the length of a fixed sized string using the value metafunction LENGTH
:
demos/tutorial/metafunctions/base.cpp
demos/tutorial/metafunctions/base.cpp.stdout
Important
Different uses of "Value":
Please note that ContainerConcept#Value
(Value<TSomeType>::Type
) is a Type Metafunction, because it returns a Type (e.g. of values in a container) and not a value.
- Objective
Write a generic function
checkContainerForDna(T & container)
that prints out a message if the value inside the container is of the typeDna
. The typeT
of the container should be specified as a template argument. Test you function with some examples.- Hint
- Use the Type Metafunction
ContainerConcept#Value
to access the (alphabet-)type of the elements in the container. - Use the Value Metafunction
IsSameType
to check for type equality.
- Use the Type Metafunction
- Solution
Your program should look something like this:
demos/tutorial/metafunctions/assignment1_solution.cpp
Note: Because the Value Metafunction
IsSameType<>
is evaluated at compile time, the part of the if-statement code that does not apply won't even appear in the compiled code. This can be an improvement to the runtime of your code.The output is the following:
demos/tutorial/metafunctions/assignment1_solution.cpp.stdout