I am assigned this program by my instructor and he wants me to convert the function to function template. I do not know how to do that. Please help me get good grades in final. Thankyou. and I am just a beginner in C++ so it would be great if you can show final steps.
#include <iostream>
#include <sstream>
#include <fstream>
using namespace std;
#include "Test.h"
struct char_list
{
char head;
char_list* tail;
};
char_list* cons(char, char_list*);
char_list* cs116();
void print_list(char_list*);
char_list* stream_to_list(istream&);
// return a list that is a subset of the 2nd parameter
// only allow those characters which pass the filter test
// determined by the boolean function (1st parameter)
char_list* filter(bool(*)(char),char_list*);
bool is_digit(char c) { return isdigit(c); }
int length(char_list*);
char_list* oop();
char_list* append(char_list*, char_list*);
class TestFP : public TestSuite::Test
{
public:
void run()
{
ostringstream oss;
ostream save_buffer(cout.rdbuf()); //current ostream buffer
cout.rdbuf(oss.rdbuf()); // redirection to stringstream
// testcase #1 check print_list and cs116() and cons
print_list(cs116());
cerr << "<" << oss.str() << ">" << endl;
test_(oss.str()=="cs116");
Templates are a mechanism for letting the compiler fill in missing information. You can see this as a smart copy-pasting function, by which the compiler generates the source code it needs to compile.
A function template example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
template <typename T>
T giveback(T t)
{
return t;
}
int main()
{
MyClass mc;
giveback<int>(10); // 0, same as...
giveback(10); // 1
giveback('A'); // 2
giveback<MyClass>(mc); // 3
}
// code generated for 0 and 1
int giveback(int t)
{
return t;
}
// code generated for 2
char giveback(char t)
{
return t;
}
// code generated for 3
MyClass giveback(MyClass t)
{
return t;
}
// class code generated
class MyArray
{
private:
int arr[100];
public:
const int * get_arr() const
{
return arr;
}
};
The sensible use of templates is writing containers and algorithms.
For example, std::vector is a class template and is also a container.
You need to specify what type of elements you want it to store before you can use it, hence:
The not-so-sensible usage is called Template Metaprogramming (TMP) and it was discovered when people saw that you can get the compiler to fill in things other than just types, such as numbers. http://en.wikipedia.org/wiki/Template_metaprogramming
By using TMP you abuse (I'd say misuse) the compiler to generate a simplified program, tailored to data known at compile-time (and not at runtime).