Brian Silverman | a8ce4c3 | 2018-08-04 23:57:09 -0700 | [diff] [blame^] | 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 | #include <boost/units/base_dimension.hpp> |
| 12 | #include <boost/units/base_unit.hpp> |
| 13 | #include <boost/units/unit.hpp> |
| 14 | #include <boost/units/quantity.hpp> |
| 15 | |
| 16 | //[runtime_conversion_factor_snippet_1 |
| 17 | |
| 18 | using boost::units::base_dimension; |
| 19 | using boost::units::base_unit; |
| 20 | |
| 21 | static const long currency_base = 1; |
| 22 | |
| 23 | struct currency_base_dimension : base_dimension<currency_base_dimension, 1> {}; |
| 24 | |
| 25 | typedef currency_base_dimension::dimension_type currency_type; |
| 26 | |
| 27 | template<long N> |
| 28 | struct currency_base_unit : |
| 29 | base_unit<currency_base_unit<N>, currency_type, currency_base + N> {}; |
| 30 | |
| 31 | typedef currency_base_unit<0> us_dollar_base_unit; |
| 32 | typedef currency_base_unit<1> euro_base_unit; |
| 33 | |
| 34 | typedef us_dollar_base_unit::unit_type us_dollar; |
| 35 | typedef euro_base_unit::unit_type euro; |
| 36 | |
| 37 | // an array of all possible conversions |
| 38 | double conversion_factors[2][2] = { |
| 39 | {1.0, 1.0}, |
| 40 | {1.0, 1.0} |
| 41 | }; |
| 42 | |
| 43 | double get_conversion_factor(long from, long to) { |
| 44 | return(conversion_factors[from][to]); |
| 45 | } |
| 46 | |
| 47 | void set_conversion_factor(long from, long to, double value) { |
| 48 | conversion_factors[from][to] = value; |
| 49 | conversion_factors[to][from] = 1.0 / value; |
| 50 | } |
| 51 | |
| 52 | BOOST_UNITS_DEFINE_CONVERSION_FACTOR_TEMPLATE((long N1)(long N2), |
| 53 | currency_base_unit<N1>, |
| 54 | currency_base_unit<N2>, |
| 55 | double, get_conversion_factor(N1, N2)); |
| 56 | |
| 57 | //] |
| 58 | |
| 59 | int main() { |
| 60 | boost::units::quantity<us_dollar> dollars = 2.00 * us_dollar(); |
| 61 | boost::units::quantity<euro> euros(dollars); |
| 62 | set_conversion_factor(0, 1, 2.0); |
| 63 | dollars = static_cast<boost::units::quantity<us_dollar> >(euros); |
| 64 | set_conversion_factor(0, 1, .5); |
| 65 | euros = static_cast<boost::units::quantity<euro> >(dollars); |
| 66 | double value = euros.value(); // = .5 |
| 67 | if(value != .5) { |
| 68 | return(1); |
| 69 | } else { |
| 70 | return(0); |
| 71 | } |
| 72 | } |