Boost logo

Boost :

From: Jonathan Turkanis (technews_at_[hidden])
Date: 2004-01-18 13:01:44

"Blake Madden" <madden_blake_at_[hidden]> wrote in message
> I am working on a string class that can represent a string constant,
but can
> be used with both char and wchar_t values. For example:
> //assigned with unicode "A HREF"
> const narrow_wide_string<> A_HREF = L"A HREF";
> //ahref will be ANSI "A HREF"
> std::string ahref = A_HREF;
> //wahref will be unicode "A HREF"
> std::wstring wahref = A_HREF;
> //returns 6
> size_t size = strlen(A_HREF);
> //returns 6
> size_t wsize = wcslen(A_HREF);
> Essentially, this solves the problem of needing to embed string
> inside of templatized string functions that are meant to work with
both char
> and wchar_t types. Currently, if you have to use string literals,
then you
> to overload your string functions: one version that takes char, the
> wchar_t. With this class, you can just make one templatized
function and
> use this class to string your constant.

I wrote a string template something like this several years ago. The
main point was to minimze copying when combining libraries which may
use different width strings depending on preprocessor definitions (I
was doing a lot of win32 programming), but it could also be used in
generic programming. An instance of xstring<Char> could be initialized
with a narrow or wide C-type string or standard string, and would
never convert it to a different width or representation unless asked
to do so.

    template< class Ch,
                    class Tr= std::char_traits<Ch> >
    struct xstring {
        /* ... */
        const char_type* c_str() const;
        const string_type str() const;
        operator const string_type&() const

Usage (win32):

    void f(TCHAR* psz)
        xstring<char> xstr(psz);
       // use xstr where a std::string or C-style string is needed,
       // regardless of the width of psz, with no copying in the
       // case that TCHAR is char and only a C-style string is
       // needed.

Usage (generic programming):

    template<typename Ch, typename Tr>
    std::basic_ostream<Ch, Tr>& operator<<(
          std::basic_ostream<Ch, Tr>& out, const Thing& t)
        out << "[Thing: " << xstring<Ch, Tr>( << "]";

I found it to me useful well beyond the case of string literals. I
didn't provide a locale argument, but this could be easily added.

How does this compare with your string?


Boost list run by bdawes at, gregod at, cpdaniel at, john at