473,385 Members | 1,901 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Templates revisited: Best coding practice

mythescriptid
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 ***
Expand|Select|Wrap|Line Numbers
  1. /* Template class to join to strings 
  2. I used templates since it will allow us to join any datatypes ( unless user defined!). 
  3. I have written two versions of same functionality 
  4. 1. uses template class 
  5. 2. using static template function 
  6. which approach is better and more generic?
  7.  
  8. */
  9.  
  10. #if !defined mystrcat_HPP
  11. #define mystrcat_HPP
  12.  
  13. #include <iostream>
  14. #include <sstream>
  15. #include <fstream>
  16. #include <time.h>
  17.  
  18. using namespace std;
  19.  
  20. /* My Exception class  to handle if failed to join strings*/
  21.  
  22. class StrCatException { 
  23. private: 
  24.     std::string mFailedMsg;
  25. public: 
  26.      StrCatException(std::string failedReason){
  27.           mFailedMsg="StrCatException: "+failedReason;
  28.  
  29.        }
  30.       void printStackTrace()
  31.       {
  32.           cout <<mFailedMsg<<endl;
  33.       }
  34. };
  35.  
  36.  
  37. /*
  38.  * Template Class used for joining any two strings( any data type)
  39.  */
  40.  
  41. template <class T,class S > 
  42. class mystrcat 
  43.     private:
  44.         T mFirstString;
  45.         S mSecondString;
  46.         //mystrcat(){} // don't allow any default construction. Can't join without any param's right?
  47.     public:
  48.         mystrcat( T aFirstString ,S aSecondString) 
  49.           {
  50.               mFirstString=aFirstString;
  51.               mSecondString =aSecondString;
  52.           }
  53.  
  54.         std::string join()
  55.         {
  56.             time_t currTime;
  57.             time(&currTime);
  58.  
  59.             std::stringstream _time2sString;
  60.             _time2sString<<currTime;
  61.  
  62.             string _sString2String;
  63.             _time2sString>>_sString2String;
  64.  
  65.             string fileName ="./strconv";
  66.             fileName +=_sString2String;// forming a unique name
  67.  
  68.             ofstream ofs (fileName.c_str());
  69.             if(!ofs) { throw StrCatException("Unable to open File for writing"); }
  70.             ofs<<mFirstString<<mSecondString;
  71.             ofs.close();
  72.             ifstream ifs(fileName.c_str());
  73.             if(!ifs) { throw StrCatException("Unable to open File for reading"); }
  74.             std::string finalString;
  75.             while(!ifs.eof())
  76.             {
  77.                 std::string cline;
  78.                 getline(ifs,cline);
  79.                 finalString += cline;
  80.             }
  81.             remove(fileName.c_str());
  82.             return finalString;
  83.         }
  84.  
  85. };
  86.  
  87. #endif
  88.  
***** end mystrcat.hpp ****

*** test class ***
Expand|Select|Wrap|Line Numbers
  1. #include "mystrcat.hpp"
  2. int main()
  3. {
  4.  
  5. try{
  6.          mystrcat<std::string,int> cCatStrs("Hello How are :",10);
  7.          std::string jS= cCatStrs.join();
  8.          cout<<"Value is : "<<jS<<endl;
  9.          cout<<"Value is : "<<mystrcat<std::string,std::string>(" second call "," Friday ").join()<<endl;
  10.          cout<<"Value is : "<<mystrcat<std::string,double>(" double call ",5645.3434).join()<<endl;
  11.          cout<<"Value is : "<<mystrcat<int,double>(1,45.3434).join()<<endl;
  12.      }
  13.      catch (StrCatException sce)
  14.      {
  15.         sce.printStackTrace();
  16.         exit(-1);
  17.      }
  18.      catch (...)
  19.      {
  20.             cout<<"Failed to "<<endl;
  21.             exit(-2);
  22.      }
  23.  
  24. }
May 26 '07 #1
5 2248
*** Second version *****
Expand|Select|Wrap|Line Numbers
  1. #if !defined STRINGCAT_HPP
  2. #define STRINGCAT_HPP
  3.  
  4. #include <iostream>
  5. #include <sstream>
  6. #include <fstream>
  7. #include <time.h>
  8.  
  9. using namespace std;
  10.  
  11. /* My Exception class  to handle if failed to join strings*/
  12.  
  13. class CatException { 
  14. private: 
  15.     std::string mFailedMsg;
  16. public: 
  17.      CatException(std::string failedReason){
  18.           mFailedMsg=failedReason;
  19.  
  20.        }
  21.       void printStackTrace()
  22.       {
  23.           cout <<"CatException:"<<mFailedMsg<<endl;
  24.       }
  25. };
  26.  
  27.  
  28. /*
  29.  * Template Class used for joining any two strings( any data type)
  30.  */
  31.  
  32. class StringCat 
  33.  
  34.     private:
  35.         StringCat( )
  36.           {
  37.           }
  38.  
  39.     public:
  40.         template <class T,class S> static std::string join(T mFirstString ,S mSecondString)
  41.         {
  42.             time_t currTime;
  43.             time(&currTime);
  44.  
  45.             std::stringstream _time2sString;
  46.             _time2sString<<currTime;
  47.  
  48.             string _sString2String;
  49.             _time2sString>>_sString2String;
  50.  
  51.             string fileName ="/tmp/strconv";
  52.             fileName +=_sString2String;// forming a unique name
  53.  
  54.             ofstream ofs (fileName.c_str());
  55.             if(!ofs) throw CatException("Unable to open File for writing");
  56.             ofs<<mFirstString<<mSecondString;
  57.             ofs.close();
  58.  
  59.             ifstream ifs(fileName.c_str());
  60.             if(!ifs) throw CatException("Unable to open File for reading"); 
  61.             std::string finalString;
  62.             while(!ifs.eof())
  63.             {
  64.                 std::string cline;
  65.                 getline(ifs,cline);
  66.                 finalString += cline;
  67.             }
  68.  
  69.             remove(fileName.c_str());
  70.             return finalString;
  71.         }
  72.  
  73. };
  74.  
  75. #endif
**** End of StringCat.hpp ****

Expand|Select|Wrap|Line Numbers
  1. #include "StringCat.hpp"
  2.  
  3. int main()
  4. {
  5.   cout <<StringCat::join("Hello", " Hi")<<endl;
  6.   cout <<StringCat::join(10, " Hi")<<endl;
  7.   cout <<StringCat::join(.01212, .2323)<<endl;
  8.   cout <<StringCat::join(10, 11)<<endl;
  9.   cout <<StringCat::join("Hello", 1231)<<endl;
  10.  
  11. }
May 26 '07 #2
weaknessforcats
9,208 Expert Mod 8TB
What are you trying to do? Recreate the STL??

You concatenate strings in the STL by:

Expand|Select|Wrap|Line Numbers
  1. string str("Hello");
  2.          str += "World";
  3.  
You append strings by:
Expand|Select|Wrap|Line Numbers
  1. string str("Hello");
  2. string str1("World");
  3. string str2;
  4.  
  5.          str2 = str + str1;
  6.  
May 27 '07 #3
What are you trying to do? Recreate the STL??
Not Really :-)
You concatenate strings in the STL by:

Expand|Select|Wrap|Line Numbers
  1. string str("Hello");
  2.          str += "World";
  3.  
You append strings by:
Expand|Select|Wrap|Line Numbers
  1. string str("Hello");
  2. string str1("World");
  3. string str2;
  4.  
  5.          str2 = str + str1;
  6.  
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 ).
May 28 '07 #4
weaknessforcats
9,208 Expert Mod 8TB
The STL solution is a different approach. Check this out:

Expand|Select|Wrap|Line Numbers
  1. //Concatenate a string and an int into a string
  2. stringstream ss;
  3. string str("The magic number is: ");
  4. int data  = 123;
  5. ss << str << data;
  6. string result;
  7. string token;
  8.   while (!ss.eof())
  9.   {
  10.      ss >> token;
  11.      result += token;
  12.      result += ' ';
  13.   }
  14. cout << result << endl;
  15.  
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.
May 28 '07 #5
The STL solution is a different approach. Check this out:

Expand|Select|Wrap|Line Numbers
  1. //Concatenate a string and an int into a string
  2. stringstream ss;
  3. string str("The magic number is: ");
  4. int data  = 123;
  5. ss << str << data;
  6. string result;
  7. string token;
  8.   while (!ss.eof())
  9.   {
  10.      ss >> token;
  11.      result += token;
  12.      result += ' ';
  13.   }
  14. cout << result << endl;
  15.  
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.
May 29 '07 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

37
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 ...
2
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...
136
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...
11
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...
10
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? ...
13
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...
16
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...
14
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...
0
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,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
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$) { } ...
0
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...
0
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
0
BarryA
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...
1
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...
0
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...
0
jinu1996
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.