Convert string to wchar.

Jonathan M Davis jmdavisProg at gmx.com
Wed Aug 3 01:10:54 PDT 2011


On Wednesday 03 August 2011 01:02:02 Jonathan M Davis wrote:
> On Wednesday 03 August 2011 09:34:53 Pelle wrote:
> > On Wed, 03 Aug 2011 08:29:09 +0200, Jacob Carlborg <doob at me.com> wrote:
> > > Yes, convert the first code point to a wchar and then throw if
> > > there's
> > > more the one character in the string.
> > 
> > Not tested, and I might be wrong, but 'to!' should work between dchar
> > and
> > wchar, no?
> > 
> > wchar to_wchar(string s) {
> > 
> >      auto c = s.front;
> >      s.popFront();
> >      assert (s.empty);
> >      return to!wchar(c);
> > 
> > }
> 
> It's debatable as to whether std.conv.to should be able to convert between
> code units like that (you _really_ shouldn't ever be using char or wchar
> outside of arrays or other ranges), but it does appear to compile, for
> better or worse.

It looks like the conversion works as long as the character in question will 
fit in the character type that you're converting to. If it doesn't fit, then it 
throws. So, it's as safe as such a conversion can be (though it still isn't 
generally a good idea to use individual chars or wchars in code).

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list