Boost logo

Boost :

From: Mihalca Bobby (bobbymihalca_at_[hidden])
Date: 2005-04-20 11:29:27


Hi.

 

I needed some std::string <-> std::wstring conversion and after

searching web for something like this found nothing except a thread

with this name here on boost.

So I made one myself, maybe if you think is worth something you will

include it in boost.

 

Here is the code:

 

template<class _RetString,class _SourceString>
_RetString string_cast(const _SourceString &src,std::locale Loc=std::locale())
{
 _RetString dst;
 typedef _SourceString::value_type _SrcValType;
 typedef _RetString::value_type _DstValType;

 typedef std::codecvt<_SrcValType,_DstValType,mbstate_t> CodeCvt;
 const CodeCvt & cvt= use_facet<CodeCvt>(Loc);
 std::mbstate_t state = std::mbstate_t();
 _SrcValType * next_in=NULL;
 _DstValType *next_out=NULL;
 dst.resize(src.size());
 while(true)
 {
  switch(cvt.out(state, src.c_str(), src.c_str() + src.size(),next_in,const_cast<_DstValType *>(dst.c_str()),const_cast<_DstValType *>(dst.c_str())+dst.size(), next_out))
  {
  case std::codecvt_base::ok:
  case std::codecvt_base::partial:
  case std::codecvt_base::error:
   // not much we can do here but guess:
  case std::codecvt_base::noconv:
   return dst;
  }
 }
 return dst;
}

and I used like this:

 

std::string strA = string_cast<std::string>( std::wstring(L"dummy example") );

 

Bobby

__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk