|
// Compile time Structured Tail Recursion
#include <iostream>
// Termination of Link List
struct End
{
};
// Node of Static Link List
template <int iData, typename Type>
struct Node
{
enum { value = iData };
typedef Type Next;
};
// Structure to add the items in Static Link List
template <typename T>
struct Add;
// Partial Template Specialization call recursively to add items
template <int iData, typename Type>
struct Add<Node<iData, Type> >
{
enum { value = iData + Add<Type>::value };
};
// Template Specialization to terminate recursion
template <>
struct Add<End>
{
enum { value = 0 };
};
// Structure to calculate the length of Static Link List
template <typename T>
struct Length;
// Partial Template Specialization call recursiveely calculate the length
template <int iData, typename Type>
struct Length<Node<iData, Type> >
{
enum { value = 1 + Length<Type>::value };
};
// Template Specialization to terminate recursion
template <> struct Length<End>
{
enum { value = 0 };
};
// Structure to multiply the items in Static Link List
template <typename T>
struct Multiply;
// Partial Template Specialization call recursively to multiply items
template <int iData, typename Type>
struct Multiply<Node<iData, Type> >
{
enum { value = iData * Multiply<Type>::value };
};
// Template Specialization to terminate recursion
template <> struct Multiply<End>
{
enum { value = 1 };
};
int main()
{
typedef Node<15, Node<20, Node<35, End> > > staticList;
std::cout << Length<staticList>::value << std::endl;
std::cout << Add<staticList>::value << std::endl;
std::cout << Multiply<staticList>::value << std::endl;
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.