By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,433 Members | 1,490 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,433 IT Pros & Developers. It's quick & easy.

Templates revisited: Best coding practice

mythescriptid
P: 15
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
Share this Question
Share on Google+
5 Replies


mythescriptid
P: 15
*** 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
Expert Mod 5K+
P: 9,197
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

mythescriptid
P: 15
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
Expert Mod 5K+
P: 9,197
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

mythescriptid
P: 15
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

Post your reply

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