1 // Boost.Units - A C++ library for zero-overhead dimensional analysis and
2 // unit/quantity manipulation and conversion
3 //
4 // Copyright (C) 2003-2008 Matthias Christian Schabel
5 // Copyright (C) 2008 Steven Watanabe
6 //
7 // Distributed under the Boost Software License, Version 1.0. (See
8 // accompanying file LICENSE_1_0.txt or copy at
9 // http://www.boost.org/LICENSE_1_0.txt)
10
11 /**
12 \file tutorial.cpp
13
14 \brief Basic tutorial using SI units.
15
16 \details
17 Tutorial
18 Defines a function that computes the work, in joules,
19 done by exerting a force in newtons over a specified distance
20 in meters and outputs the result to std::cout.
21
22 Also code for computing the complex impedance
23 using std::complex<double> as the value type.
24
25 Output:
26 @verbatim
27 //[tutorial_output
28 F = 2 N
29 dx = 2 m
30 E = 4 J
31
32 V = (12.5,0) V
33 I = (3,4) A
34 Z = (1.5,-2) Ohm
35 I*Z = (12.5,0) V
36 I*Z == V? true
37 //]
38 @endverbatim
39 */
40
41 //[tutorial_code
42 #include <complex>
43 #include <iostream>
44
45 #include <boost/typeof/std/complex.hpp>
46
47 #include <boost/units/systems/si/energy.hpp>
48 #include <boost/units/systems/si/force.hpp>
49 #include <boost/units/systems/si/length.hpp>
50 #include <boost/units/systems/si/electric_potential.hpp>
51 #include <boost/units/systems/si/current.hpp>
52 #include <boost/units/systems/si/resistance.hpp>
53 #include <boost/units/systems/si/io.hpp>
54
55 using namespace boost::units;
56 using namespace boost::units::si;
57
58 constexpr
59 quantity<energy>
work(const quantity<force> & F,const quantity<length> & dx)60 work(const quantity<force>& F, const quantity<length>& dx)
61 {
62 return F * dx; // Defines the relation: work = force * distance.
63 }
64
main()65 int main()
66 {
67 /// Test calculation of work.
68 quantity<force> F(2.0 * newton); // Define a quantity of force.
69 quantity<length> dx(2.0 * meter); // and a distance,
70 quantity<energy> E(work(F,dx)); // and calculate the work done.
71
72 std::cout << "F = " << F << std::endl
73 << "dx = " << dx << std::endl
74 << "E = " << E << std::endl
75 << std::endl;
76
77 /// Test and check complex quantities.
78 typedef std::complex<double> complex_type; // double real and imaginary parts.
79
80 // Define some complex electrical quantities.
81 quantity<electric_potential, complex_type> v = complex_type(12.5, 0.0) * volts;
82 quantity<current, complex_type> i = complex_type(3.0, 4.0) * amperes;
83 quantity<resistance, complex_type> z = complex_type(1.5, -2.0) * ohms;
84
85 std::cout << "V = " << v << std::endl
86 << "I = " << i << std::endl
87 << "Z = " << z << std::endl
88 // Calculate from Ohm's law voltage = current * resistance.
89 << "I * Z = " << i * z << std::endl
90 // Check defined V is equal to calculated.
91 << "I * Z == V? " << std::boolalpha << (i * z == v) << std::endl
92 << std::endl;
93 return 0;
94 }
95 //]
96