Let us see
how we can simply print a name using templates in C++ using the following
example:
/*
*
File: helloWorld.cpp
*
Author: Praveen Vinny
*
*
Created on June 6, 2016, 3:04 PM
*/
#include <iostream>
#include <sstream>
using namespace std;
template<typename T>
string printMe(const T &value) {
ostringstream temp;
temp << value;
return temp.str();
}
/**
* This
is the main() method where the program main() method is defined.
*
@param argc
*
@param argv
*
@return
*/
int main(int argc, char** argv) {
string name;
cout<<"Enter a name: ";
cin>>name;
cout<<"Hello
"<<printMe<string>(name)<<"!"<<endl;
return 0;
}
Here is how this program works:
1.
We
input a name from user into the string called as name.
2.
We
are passing this to a template function mentioning the type of the argument as
string during its call.
3.
We
create an object of the ostringstream to store this value. We use the insertion
operator(<<) to store the value in the template variable into the object
of osringstream.
4.
We
return the value after converting it into string which will be returned and
printed on screen.
Output:
Enter a name: Praveen
Hello Praveen!
RUN SUCCESSFUL (total time: 3s)