safe_cast.xml 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE section PUBLIC "-//Boost//DTD BoostBook XML V1.1//EN"
  3. "http://www.boost.org/tools/boostbook/dtd/boostbook.dtd">
  4. <section id="safe_numerics.safe_cast">
  5. <title>safe_cast&lt;T, U&gt;</title>
  6. <section>
  7. <title>Synopsis</title>
  8. <programlisting>template&lt;class T, class U&gt;
  9. T safe_cast(const U &amp; u);</programlisting>
  10. </section>
  11. <section>
  12. <title>Description</title>
  13. <para>Converts one <link linkend="safe_numerics.numeric">Numeric</link>
  14. type to another. Throws an <code>std::out_of_range</code> exception if
  15. such a conversion is not possible without changing the value. This
  16. function is part of the implementation of the safe numerics library. It's
  17. been made publicly because it might be useful in related contexts.</para>
  18. </section>
  19. <section>
  20. <title>Type requirements</title>
  21. <informaltable>
  22. <tgroup cols="2">
  23. <colspec align="left"/>
  24. <colspec align="left" colwidth="3*"/>
  25. <thead>
  26. <row>
  27. <entry align="left">Type</entry>
  28. <entry align="left">Requirements</entry>
  29. </row>
  30. </thead>
  31. <tbody>
  32. <row>
  33. <entry><code>T</code></entry>
  34. <entry><link
  35. linkend="safe_numerics.numeric">Numeric</link></entry>
  36. </row>
  37. <row>
  38. <entry><code>U </code></entry>
  39. <entry><link
  40. linkend="safe_numerics.numeric">Numeric</link></entry>
  41. </row>
  42. </tbody>
  43. </tgroup>
  44. </informaltable>
  45. </section>
  46. <section>
  47. <title>Preconditions</title>
  48. <para>The value of u must be representable by the type <code>T</code>. If
  49. this is not true, an <code>std::out_of_range</code> exception will be
  50. thrown.</para>
  51. </section>
  52. <section>
  53. <title>Header</title>
  54. <para><filename><ulink url="../../include/safe_cast.hpp">#include
  55. &lt;boost/numeric/safe_cast.hpp&gt; </ulink></filename></para>
  56. </section>
  57. <section>
  58. <title>Example of use</title>
  59. <programlisting>#include &lt;boost/numeric/safe_cast.hpp&gt;
  60. #include &lt;boost/numeric/safe_integer.hpp&gt;
  61. void f(){
  62. safe_integer&lt;char&gt; i;
  63. unsigned char j;
  64. i = 1;
  65. j = safe_cast&lt;unsigned char&gt;(i); // ok
  66. i = -1;
  67. j = safe_cast&lt;unsigned char&gt;(i); // throws std::out_of_range exception
  68. i = 1024;
  69. j = safe_cast&lt;unsigned char&gt;(i); // throws std::out_of_range exception
  70. }</programlisting>
  71. </section>
  72. </section>