TCHAR array, std::string or std::wstring - none of them !

Posted by Quakeboy Comments

Having confusion about how to make flexible use of strings in your C++ application. Here is the solution I got after googling. I love the way C++ macros help in maintaining code well

You don't have to use TCHAR, std::string or std::wstring in your application directly and make it rigid. Make use of the code below and then use the typedef - String or tstring. Now your strings in your C++ application becomes very flexible.

Converting 'TChar' to 'String' in C++ - GameDev.Net Discussion Forums
TCHAR is just a typedef that depending on your compilation configuration (whether you have #define'd UNICODE or not) defaults to char or wchar. Note that you don't necessarily need to #define UNICODE as part of your code. You may also pass it to your target compiler via some preprocessor definition argument, such as /D in microsoft's visual C++ compiler.

Standard Template Library on the other hand supports both ASCII (with std::string) and wide character sets (with std::wstring). All you need to do is to typedef String as either std::string or std::wstring depending on your compilation configuration, if flexibility is what you're aiming for. Something like this might prove useful:

#ifndef UNICODE
typedef std::string String
#else
typedef std::wstring String
#endif



converting std::string to TCHAR
You could do a compile time version of string like this:

#include

namespace std {

#if defined _UNICODE || defined UNICODE

typedef wstring tstring;

#else

typedef string tstring;

#endif

}

Then you could use tstring instead of string and it would depend on the compile options.

Tom
Labels: