473,802 Members | 2,267 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Templates revisited: Best coding practice

mythescriptid
15 New Member
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 2271
mythescriptid
15 New Member
*** 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 Recognized Expert Moderator Expert
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
15 New Member
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 Recognized Expert Moderator Expert
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
15 New Member
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
2166
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
2
1592
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...
136
9461
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,...
11
2555
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....
10
3005
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
13
3118
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....
16
2823
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
14
2205
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,
0
9562
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,...
0
10536
Oralloy
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...
0
10304
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 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...
0
9114
agi2029
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...
1
7598
isladogs
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...
0
5494
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...
0
5622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4270
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
2
3792
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.