Re: What are some simple, practical examples of template
metaprogramming?
[Please do not mail me a copy of your followup]
"K. Frank" <kfrank29.c@googlemail.com> spake the secret code
<935442e7-2b1a-4ce0-a96c-0c2345cf13b1@googlegroups.com> thusly:
What are some simple examples that illustrate the benefits of
template metaprogramming?
A type traits class that specifies additional compile-time information
associated with a type is a good, small example IMO.
One interesting trick is to use a traits class to associate other
static compile-time metadata with an enum value.
Here is a small example of template meta-programming IMO:
template <typename T>
struct type_encoder
{
typedef no_op_encoder<T> encoder_type;
};
template <>
struct type_encoder<char>
{
typedef utf8_encoder encoder_type;
};
template <>
struct type_encoder<char16_t>
{
typedef utf16_encoder encoder_type;
};
type_encoder<T>::encoder_type is a template meta-function that yields
the type of an encoder class that is appropriate for type T. The
first definition says that no_op_encoder<T> is used unless we have a
specialization. Then there follows two specializations for T=char and
T=char16_t.
--
"The Direct3D Graphics Pipeline" free book <http://tinyurl.com/d3d-pipeline>
The Computer Graphics Museum <http://computergraphicsmuseum.org>
The Terminals Wiki <http://terminals.classiccmp.org>
Legalize Adulthood! (my blog) <http://legalizeadulthood.wordpress.com>
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]