• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
7  <section>
8    <title>Synopsis</title>
9
10    <programlisting>template&lt;class T, class U&gt;
11T safe_cast(const U &amp; u);</programlisting>
12  </section>
13
14  <section>
15    <title>Description</title>
16
17    <para>Converts one <link linkend="safe_numerics.numeric">Numeric</link>
18    type to another. Throws an <code>std::out_of_range</code> exception if
19    such a conversion is not possible without changing the value. This
20    function is part of the implementation of the safe numerics library. It's
21    been made publicly because it might be useful in related contexts.</para>
22  </section>
23
24  <section>
25    <title>Type requirements</title>
26
27    <informaltable>
28      <tgroup cols="2">
29        <colspec align="left"/>
30
31        <colspec align="left" colwidth="3*"/>
32
33        <thead>
34          <row>
35            <entry align="left">Type</entry>
36
37            <entry align="left">Requirements</entry>
38          </row>
39        </thead>
40
41        <tbody>
42          <row>
43            <entry><code>T</code></entry>
44
45            <entry><link
46            linkend="safe_numerics.numeric">Numeric</link></entry>
47          </row>
48
49          <row>
50            <entry><code>U </code></entry>
51
52            <entry><link
53            linkend="safe_numerics.numeric">Numeric</link></entry>
54          </row>
55        </tbody>
56      </tgroup>
57    </informaltable>
58  </section>
59
60  <section>
61    <title>Preconditions</title>
62
63    <para>The value of u must be representable by the type <code>T</code>. If
64    this is not true, an <code>std::out_of_range</code> exception will be
65    thrown.</para>
66  </section>
67
68  <section>
69    <title>Header</title>
70
71    <para><filename><ulink url="../../include/safe_cast.hpp">#include
72    &lt;boost/numeric/safe_cast.hpp&gt; </ulink></filename></para>
73  </section>
74
75  <section>
76    <title>Example of use</title>
77
78    <programlisting>#include &lt;boost/numeric/safe_cast.hpp&gt;
79#include &lt;boost/numeric/safe_integer.hpp&gt;
80
81void f(){
82    safe_integer&lt;char&gt; i;
83    unsigned char j;
84    i = 1;
85    j = safe_cast&lt;unsigned char&gt;(i);  // ok
86    i = -1;
87    j = safe_cast&lt;unsigned char&gt;(i);  // throws std::out_of_range exception
88    i = 1024;
89    j = safe_cast&lt;unsigned char&gt;(i);  // throws std::out_of_range exception
90}</programlisting>
91  </section>
92</section>
93