Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef a std::string - Best practice

Tags:

c++

typedef

I am writing a library in standard C++ which does the phonetic conversion. I have used std::string as of now. But in future I may have to change this to someother (std::wstring or something else). So I need to write my library in such a way that I can switch this easily. I have done the following so far to achieve this.

  1. Created a header file which will be used by all CPP files
  2. Added a "typedef std::string" to this and used the new name everywhere in the file.

If I need to change the type, I can simply change in the header file and it will be reflected everywhere. I'd appreciate if someone can see this is the correct approach or is there a better way to do this?

Thanks

like image 929
Navaneeth K N Avatar asked Jan 01 '09 03:01

Navaneeth K N


Video Answer


2 Answers

You can write template functions that will work with either type of string, or for that matter anything that has the proper methods.

If you do the typedef as you suggest, you will need to change all your code in the future when you change the typedef. I'd recommend against it.

Edit: the point is that string and wstring are not interchangeable. Sure, you'll be able to update your library by changing a single line, but that's just the start - changing the typedef means you're changing the public API of your library. You'll have to change and test all of the code that interacts with your library, and this might represent the majority of the work involved. It's even possible that a simple search and replace is sufficient to update your library, and then the typedef has bought you nothing.

There's value in sticking to the standard types that everyone knows and understands.

like image 54
Mark Ransom Avatar answered Oct 15 '22 21:10

Mark Ransom


I think typedeffing std::string is reasonable. You are still bound to an interface though. If you ever switch to a string implementation with an incompatible interface you can change the value of your typedef to some adapter class. In C++, you can do this with minimal to no overhead. Changing to a new string type then implies changing the adapter class. If you find yourself changing the adapter often you might set it as a template.

You are still not immune however from others (or yourself in a later time) forgetting about the typedef and using std::string directly.

like image 28
wilhelmtell Avatar answered Oct 15 '22 20:10

wilhelmtell