Click here to Skip to main content
15,893,190 members
Articles / Programming Languages / C++

Recursion Primer using C++: Part 3

Rate me:
Please Sign up or sign in to vote.
4.80/5 (12 votes)
6 May 2011CPOL16 min read 34.6K   332   27  
In this article, we try to combine compile time/runtime and structure/generative with five different types of recursion.
// 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader American Institute for Research
United States United States
Working as a Team leader in American Institute for Research

Comments and Discussions