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.
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With