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 2271
*** 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
letting tuples-like objects (x,y,z=0) acting as functions on other
tuples I wonder why this would not be a good starting point of
rethinking anonymus functions?
In Georges proposition the action is
|
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 that doesent use much memory.
I know a lot of C++ programmers ,and they tolded me,
that C++ templates are real solution for dynamical memory
use programming.I readed 3 books about C++ , but I don't
have a practice and a mass things about templates...
|
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 code
was littered with document.all and eval, for example, and I wanted to create
a practical list of best practices that they could easily put to use.
The above URL is version 1.0 (draft) that resulted. IMO, it is not a
replacement for the FAQ,...
|
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 well as learning C#, I think that it's way
overdue for me to start learning C++ Templates (I've been learning it for
about 5 years now).
I think that adding this type of functionality would be a good exercise
to help learn template programming....
|
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?
public class MyClass
private _variableName as integer
public property VariableName as integer
| |
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 sorts of clients. Mine are all
small businesses whose sites will never reach those sorts of scales. I
deal with businesses whose sites get maybe a few hundred visitors per
day (some not even that much) and get no more than ten orders per day....
|
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 efficient
navigating within Visual Studio 2005. Let's say your project (or
solution) has dozens of forms and hundreds or even thousands of
routines.
Two Questions:
1) BUILT-IN to Visual Studio 2005. What ideas do you have to quickly
|
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 the .cpp files. After some
reading, I found that the only way to do this is to add the actual
template instantiations in the .cpp file. But, how do you do that if
you're not working with built-in types? For example, a template class
might be,
|
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
| |
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |