D Programming Language 2.0

Last update Wed Aug 1 09:43:21 2012

# std.conv

A one-stop shop for converting values from one type to another.

License:
Boost License 1.0.

Authors:
Walter Bright, Andrei Alexandrescu, Shin Fujishiro, Adam D. Ruppe, Kenji Hara

Source:
std/conv.d

class ConvException: object.Exception;
  Thrown on conversion errors.

class ConvOverflowException: std.conv.ConvException;
  Thrown on conversion overflow errors.

template to(T)
  Entry point that dispatches to the appropriate conversion primitive. Client code normally calls to!TargetType(value) (and not some variant of toImpl).

T toImpl(T, S)(S value);
  If the source type is implicitly convertible to the target type, to simply performs the implicit conversion.

T toImpl(T, S)(S value);
  Deprecated. It will be removed in September 2012. Please define opCast for user-defined types instead of a to function. to will now use opCast.

  Object-to-non-object conversions look for a method "to" of the source object.

  Example:

      class Date
      {
          T to(T)() if(is(T == long))
          {
              return timestamp;
          }
          ...
      }

      unittest
      {
          debug(conv) scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " succeeded.");
          auto d = new Date;
          auto ts = to!long(d); // same as d.to!long()
      }

T toImpl(T, S)(S value);
  When source type supports member template function opCast, is is used.

T toImpl(T, S)(S value);
T toImpl(T, S)(S value);
  When target type supports 'converting construction', it is used.
  - If target type is struct, T(value) is used.
  - If target type is class, new T(value) is used.

T toImpl(T, S)(S value);
  Object-to-object conversions by dynamic casting throw exception when the source is non-null and the target is null.

T toImpl(T, S)(S value);
T toImpl(T, S)(S value, uint radix);
  Stringnize conversion from all types is supported.
  - String to string conversion works for any two string types having (char, wchar, dchar) character widths and any combination of qualifiers (mutable, const, or immutable).
  - Converts array (other than strings) to string. Each element is converted by calling to!T.
  - Associative array to string conversion. Each element is printed by calling to!T.
  - Object to string conversion calls toString against the object or returns "null" if the object is null.
  - Struct to string conversion calls toString against the struct if it is defined.
  - For structs that do not define toString, the conversion to string produces the list of fields.
  - Enumerated types are converted to strings as their symbolic names.
  - Boolean values are printed as "true" or "false".
  - char, wchar, dchar to a string type.
  - Unsigned or signed integers to strings.
    [special case]
      Convert integral value to string in radix radix. radix must be a value from 2 to 36. value is treated as a signed value only if radix is 10. The characters A through Z are used to represent values 10 through 36.
  - All floating point types to all string types.
  - Pointer to string conversions prints the pointer as a size_t value. If pointer is char*, treat it as C-style strings.

T toImpl(T, S)(S s, in T leftBracket, in T separator = ", ", in T rightBracket = "]");
T toImpl(T, S)(ref S s, in T leftBracket, in T separator = " ", in T rightBracket = "]");
T toImpl(T, S)(S s, in T leftBracket, in T keyval = ":", in T separator = ", ", in T rightBracket = "]");
T toImpl(T, S)(S s, in T nullstr);
T toImpl(T, S)(S s, in T left, in T separator = ", ", in T right = ")");
  Deprecated. It will be removed in January 2013. Please use std.format.formattedWrite instead.

  Conversions to string with optional configures.

T toImpl(T, S)(S value);
  Narrowing numeric-numeric conversions throw when the value does not fit in the narrower type.

T toImpl(T, S)(S value);
  Array-to-array conversion (except when target is a string type) converts each element in turn by using to.

T toImpl(T, S)(S value);
  Associative array to associative array conversion converts each key and each value in turn.

T toImpl(T, S)(S value);
T toImpl(T, S)(S value, uint radix);
  String to non-string conversion runs parsing.
  - When the source is a wide string, it is first converted to a narrow string and then parsed.
  - When the source is a narrow string, normal text parsing occurs.

template roundTo(Target)
  Rounded conversion from floating point to integral.

  Example:

      assert(roundTo!int(3.14) == 3);
      assert(roundTo!int(3.49) == 3);
      assert(roundTo!int(3.5) == 4);
      assert(roundTo!int(3.999) == 4);
      assert(roundTo!int(-3.14) == -3);
      assert(roundTo!int(-3.49) == -3);
      assert(roundTo!int(-3.5) == -4);
      assert(roundTo!int(-3.999) == -4);

  Rounded conversions do not work with non-integral target types.

Target parse(Target, Source)(ref Source s);
Target parse(Target, Source)(ref Source s, uint radix);
  The parse family of functions works quite like the to family, except that (1) it only works with character ranges as input, (2) takes the input by reference and advances it to the position following the conversion, and (3) does not throw if it could not convert the entire input. It still throws if an overflow occurred during conversion or if no character of the input was meaningfully converted.

  Example:

      string test = "123 \t  76.14";
      auto a = parse!uint(test);
      assert(a == 123);
      assert(test == " \t  76.14"); // parse bumps string
      munch(test, " \t\n\r"); // skip ws
      assert(test == "76.14");
      auto b = parse!double(test);
      assert(b == 76.14);
      assert(test == "");

Target parse(Target, Source)(ref Source s);
  Parsing one character off a string returns the character and bumps the string up one position.

Target parse(Target, Source)(ref Source s, dchar lbracket = '[', dchar rbracket = ']', dchar comma = ',');
Target parse(Target, Source)(ref Source s, dchar lbracket = '[', dchar rbracket = ']', dchar comma = ',');
  Parses an array from a string given the left bracket (default '['), right bracket (default ']'), and element seprator (by default ',').

Target parse(Target, Source)(ref Source s, dchar lbracket = '[', dchar rbracket = ']', dchar keyval = ':', dchar comma = ',');
  Parses an associative array from a string given the left bracket (default '['), right bracket (default ']'), key-value separator (default ':'), and element seprator (by default ',').

string text(T...)(T args);
wstring wtext(T...)(T args);
dstring dtext(T...)(T args);
  Convenience functions for converting any number and types of arguments into text (the three character widths).

  Example:

      assert(text(42, ' ', 1.5, ": xyz") == "42 1.5: xyz");
      assert(wtext(42, ' ', 1.5, ": xyz") == "42 1.5: xyz"w);
      assert(dtext(42, ' ', 1.5, ": xyz") == "42 1.5: xyz"d);

int octal(string num)();
long octal(string num)();
uint octal(string num)();
ulong octal(string num)();
template octal(alias s) if (isIntegral!(typeof(s)))
  The octal facility is intended as an experimental facility to replace octal literals starting with '0', which many find confusing. Using octal!177 or octal!"177" instead of 0177 as an octal literal makes code clearer and the intent more visible. If use of this facility becomes preponderent, a future version of the language may deem old-style octal literals deprecated.

  The rules for strings are the usual for literals: If it can fit in an int, it is an int. Otherwise, it is a long. But, if the user specifically asks for a long with the L suffix, always give the long. Give an unsigned iff it is asked for with the U or u suffix. Octals created from integers preserve the type of the passed-in integral.

  Example:

      // same as 0177
      auto x = octal!177;
      // octal is a compile-time device
      enum y = octal!160;
      // Create an unsigned octal
      auto z = octal!"1_000_000u";

T* emplace(T)(T* chunk);
T* emplace(T)(T* chunk);
  Given a pointer chunk to uninitialized memory (but already typed as T), constructs an object of non-class type T at that address.

  This function can be @trusted if the corresponding constructor of T is @safe.

  Returns:
  A pointer to the newly constructed object (which is the same as chunk).

T* emplace(T, Args...)(T* chunk, Args args);
  Given a pointer chunk to uninitialized memory (but already typed as a non-class type T), constructs an object of type T at that address from arguments args.

  This function can be @trusted if the corresponding constructor of T is @safe.

  Returns:
  A pointer to the newly constructed object (which is the same as chunk).

T emplace(T, Args...)(void[] chunk, Args args);
  Given a raw memory area chunk, constructs an object of class type T at that address. The constructor is passed the arguments Args. The chunk must be as least as large as T needs and should have an alignment multiple of T's alignment. (The size of a class instance is obtained by using _traits(classInstanceSize, T)).

  This function can be @trusted if the corresponding constructor of T is @safe.

  Returns:
  A pointer to the newly constructed object.

T* emplace(T, Args...)(void[] chunk, Args args);
  Given a raw memory area chunk, constructs an object of non-class type T at that address. The constructor is passed the arguments args, if any. The chunk must be as least as large as T needs and should have an alignment multiple of T's alignment.

  This function can be @trusted if the corresponding constructor of T is @safe.

  Returns:
  A pointer to the newly constructed object.

Copyright Digital Mars 2007-. | Page generated by Ddoc.