Hi All,
I know templates and STL might have been discussed many a times here, I'm bit of newbie as far as templates are concerned and was itching to test my new found linking of templates. I would like to continue discussing pro/cons and best methods of template implementation.
As a start I'm posting two simple template classes I have written for your review and let me know how can they be further improved and do they follow standard STL?
Feel free to post some good/innovative Template code you might have written ( as long as it does not infringe copyright ;-) )
Thanks in advance.
Hari.
*** CODE listing *** - /* Template class to join to strings
-
I used templates since it will allow us to join any datatypes ( unless user defined!).
-
I have written two versions of same functionality
-
1. uses template class
-
2. using static template function
-
which approach is better and more generic?
-
-
*/
-
-
#if !defined mystrcat_HPP
-
#define mystrcat_HPP
-
-
#include <iostream>
-
#include <sstream>
-
#include <fstream>
-
#include <time.h>
-
-
using namespace std;
-
-
/* My Exception class to handle if failed to join strings*/
-
-
class StrCatException {
-
private:
-
std::string mFailedMsg;
-
public:
-
StrCatException(std::string failedReason){
-
mFailedMsg="StrCatException: "+failedReason;
-
-
}
-
void printStackTrace()
-
{
-
cout <<mFailedMsg<<endl;
-
}
-
};
-
-
-
/*
-
* Template Class used for joining any two strings( any data type)
-
*/
-
-
template <class T,class S >
-
class mystrcat
-
{
-
private:
-
T mFirstString;
-
S mSecondString;
-
//mystrcat(){} // don't allow any default construction. Can't join without any param's right?
-
public:
-
mystrcat( T aFirstString ,S aSecondString)
-
{
-
mFirstString=aFirstString;
-
mSecondString =aSecondString;
-
}
-
-
std::string join()
-
{
-
time_t currTime;
-
time(&currTime);
-
-
std::stringstream _time2sString;
-
_time2sString<<currTime;
-
-
string _sString2String;
-
_time2sString>>_sString2String;
-
-
string fileName ="./strconv";
-
fileName +=_sString2String;// forming a unique name
-
-
ofstream ofs (fileName.c_str());
-
if(!ofs) { throw StrCatException("Unable to open File for writing"); }
-
ofs<<mFirstString<<mSecondString;
-
ofs.close();
-
ifstream ifs(fileName.c_str());
-
if(!ifs) { throw StrCatException("Unable to open File for reading"); }
-
std::string finalString;
-
while(!ifs.eof())
-
{
-
std::string cline;
-
getline(ifs,cline);
-
finalString += cline;
-
}
-
remove(fileName.c_str());
-
return finalString;
-
}
-
-
};
-
-
#endif
-
***** end mystrcat.hpp ****
*** test class *** - #include "mystrcat.hpp"
-
int main()
-
{
-
-
try{
-
mystrcat<std::string,int> cCatStrs("Hello How are :",10);
-
std::string jS= cCatStrs.join();
-
cout<<"Value is : "<<jS<<endl;
-
cout<<"Value is : "<<mystrcat<std::string,std::string>(" second call "," Friday ").join()<<endl;
-
cout<<"Value is : "<<mystrcat<std::string,double>(" double call ",5645.3434).join()<<endl;
-
cout<<"Value is : "<<mystrcat<int,double>(1,45.3434).join()<<endl;
-
}
-
catch (StrCatException sce)
-
{
-
sce.printStackTrace();
-
exit(-1);
-
}
-
catch (...)
-
{
-
cout<<"Failed to "<<endl;
-
exit(-2);
-
}
-
-
}
5 2248
*** Second version ***** - #if !defined STRINGCAT_HPP
-
#define STRINGCAT_HPP
-
-
#include <iostream>
-
#include <sstream>
-
#include <fstream>
-
#include <time.h>
-
-
using namespace std;
-
-
/* My Exception class to handle if failed to join strings*/
-
-
class CatException {
-
private:
-
std::string mFailedMsg;
-
public:
-
CatException(std::string failedReason){
-
mFailedMsg=failedReason;
-
-
}
-
void printStackTrace()
-
{
-
cout <<"CatException:"<<mFailedMsg<<endl;
-
}
-
};
-
-
-
/*
-
* Template Class used for joining any two strings( any data type)
-
*/
-
-
class StringCat
-
{
-
-
private:
-
StringCat( )
-
{
-
}
-
-
public:
-
template <class T,class S> static std::string join(T mFirstString ,S mSecondString)
-
{
-
time_t currTime;
-
time(&currTime);
-
-
std::stringstream _time2sString;
-
_time2sString<<currTime;
-
-
string _sString2String;
-
_time2sString>>_sString2String;
-
-
string fileName ="/tmp/strconv";
-
fileName +=_sString2String;// forming a unique name
-
-
ofstream ofs (fileName.c_str());
-
if(!ofs) throw CatException("Unable to open File for writing");
-
ofs<<mFirstString<<mSecondString;
-
ofs.close();
-
-
ifstream ifs(fileName.c_str());
-
if(!ifs) throw CatException("Unable to open File for reading");
-
std::string finalString;
-
while(!ifs.eof())
-
{
-
std::string cline;
-
getline(ifs,cline);
-
finalString += cline;
-
}
-
-
remove(fileName.c_str());
-
return finalString;
-
}
-
-
};
-
-
#endif
**** End of StringCat.hpp **** - #include "StringCat.hpp"
-
-
int main()
-
{
-
cout <<StringCat::join("Hello", " Hi")<<endl;
-
cout <<StringCat::join(10, " Hi")<<endl;
-
cout <<StringCat::join(.01212, .2323)<<endl;
-
cout <<StringCat::join(10, 11)<<endl;
-
cout <<StringCat::join("Hello", 1231)<<endl;
-
-
}
What are you trying to do? Recreate the STL??
You concatenate strings in the STL by: -
string str("Hello");
-
str += "World";
-
You append strings by: -
string str("Hello");
-
string str1("World");
-
string str2;
-
-
str2 = str + str1;
-
What are you trying to do? Recreate the STL??
Not Really :-)
You concatenate strings in the STL by: -
string str("Hello");
-
str += "World";
-
You append strings by: -
string str("Hello");
-
string str1("World");
-
string str2;
-
-
str2 = str + str1;
-
I know strings can be joined , actually I was writing some code where I need to join a String and a Int. And std::string does not allow that. So I wrote my own join method which can join two different data types ( like string + int, string+float etc ).
The STL solution is a different approach. Check this out: -
//Concatenate a string and an int into a string
-
stringstream ss;
-
string str("The magic number is: ");
-
int data = 123;
-
ss << str << data;
-
string result;
-
string token;
-
while (!ss.eof())
-
{
-
ss >> token;
-
result += token;
-
result += ' ';
-
}
-
cout << result << endl;
-
Here a stringstream is used and you just insert your data into the stream. Everything is converted to char since all of the templates are specialzed on char (or wchar_t but's that a different story). Then you just use the extractor of the stream to fetch the tokens. You build the result by appending the token and a space.
The type of code you are trying to get working is a duplication of STL features.
The STL solution is a different approach. Check this out: -
//Concatenate a string and an int into a string
-
stringstream ss;
-
string str("The magic number is: ");
-
int data = 123;
-
ss << str << data;
-
string result;
-
string token;
-
while (!ss.eof())
-
{
-
ss >> token;
-
result += token;
-
result += ' ';
-
}
-
cout << result << endl;
-
Here a stringstream is used and you just insert your data into the stream. Everything is converted to char since all of the templates are specialzed on char (or wchar_t but's that a different story). Then you just use the extractor of the stream to fetch the tokens. You build the result by appending the token and a space.
The type of code you are trying to get working is a duplication of STL features.
agree stringstream does allow us to use "<<" operator to write(append) and read back into string. But I find it to be confusing and it eats up the spaces in a string for example:
if str = " Hello here are _sp_ _sp_ _sp_ many spaces in ";// _sp_ to represent a single white space
even if I use your logic ( as above ) would still lose the multiple spaces.
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Kay Schluehr |
last post by:
Since George Sakkis proposed a new way of doing list comprehensions
http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/ac5023ad18b2835f/d3ff1b81fa70c8a7#d3ff1b81fa70c8a7
...
|
by: Bore Biko |
last post by:
Dear,
I am an ordinary C programmer and I am most interesed
about dynamical data structuring and programming,
I don't like to use matricess and rows, I like to program
with practical programs...
|
by: Matt Kruse |
last post by:
http://www.JavascriptToolbox.com/bestpractices/
I started writing this up as a guide for some people who were looking for
general tips on how to do things the 'right way' with Javascript. Their...
|
by: Brent Ritchie |
last post by:
Hello all,
I have been using C# in my programming class and I have grown quite fond
of C# properties. Having a method act like a variable that I can control
access to is really something. As...
|
by: Ren |
last post by:
Hi All,
I'm still rather new at vb.net and would like to know the proper way to access
private varibables in a class. Do I access the variable directly or do I use
the public property?
...
|
by: Alan Silver |
last post by:
Hello,
MSDN (amongst other places) is full of helpful advice on ways to do data
access, but they all seem geared to wards enterprise applications. Maybe
I'm in a minority, but I don't have those...
|
by: Rex |
last post by:
Hi All - I have a question that I think MIGHT be of interest to a
number of us developers. I am somewhat new to VIsual Studio 2005 but
not new to VB. I am looking for ideas about quick and...
|
by: aaragon |
last post by:
Hi everyone,
I've been writing some code and so far I have all the code written in
the .h files in order to avoid the linker errors. I'm using templates.
I wanted to move the implementations to...
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
| |