In my travels, I have found three primary uses for template parameters as fundamental types:
One is building a function template that takes a C-style array. That's what you've posted here, but more commonly I have seen this applies to char
arrays, as with:
template <size_t N, typename Char>
string MakeString (Char const (&chars)[N])
{
return string (chars, N);
}
int main()
{
string hi = MakeString ("Hello");
cout << hi;
}
Another use is building a kind of cheap attribute system using template metaprogramming. For example, suppose you have a bunch of classes meant to represent messages in some wire protocol, and for testing purposes you want to compare the actual size of the message class with what the specifications say the size should be.
enum MsgType
{
MsgType_Foo,
MsgType_Bar
};
class FooMsg
{
uint32_t mField;
char mName [9];
};
class BarMsg
{
char mPrice [8];
static const size_t SpecSize = 8;
};
template <MsgType MT> size_t SpecSize();
template <> size_t SpecSize <MsgType_Foo> ()
{
return 13;
}
template <> size_t SpecSize <MsgType_Bar> ()
{
return 9;
}
int main()
{
assert (SpecSize <MsgType_Foo> () == sizeof (FooMsg));
assert (SpecSize <MsgType_Bar> () == sizeof (BarMsg));
}
Note that if you run this program the assertions will fail unless you do something platform-specific (like #pragma pack (push, 1)
) to fix the packing. This is one of the things the tests are intended to catch!
Finally, another common use is more specific but the technique can be applied to your own code. In Boost.Tuple, and now C++11, the tuple
class uses a template function get<size_t>
as a means to access the elements. Here is an example taken from en.cppreference.com:
#include <iostream>
#include <string>
#include <tuple>
int main()
{
auto t = std::make_tuple(1, "Foo", 3.14);
// index-based access
std::cout << "(" << std::get<0>(t) << ", " << std::get<1>(t)
<< ", " << std::get<2>(t) << ")\n";
}
I guess you could think of this as a specialization of both of previous examples. It's yet more template metaprogramming trickery that turns out to be quite useful in certain situations.