runtime_conversion_factor.cpp 2.1 KB

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