0

Both, std::chrono::duration and boost::units::quantity<time> represent the same physical dimension. What I'm looking for is a way to use values of these types interchangeable, e.g. use a quantity<time> where a std::clock::duration is required and vice versa.

Please note that I already have a conversion function, but doing the conversion manually feels clumsy. The compiler should be able to do the conversion automatically.

An example would be assigning chrono_literals to a quantity:

quantity<time> q = 2h;

My current conversion function:

/// <summary>
/// Convert a std::chrono::duration to a boost::unit time quantity
/// </summary>
/// <typeparam name="_Period1">a std::ratio representing the tick period (i.e. the number of seconds per tick)</typeparam>
/// <typeparam name="_Type">an arithmetic type representing the number of ticks</typeparam>
/// <param name="in">the duration to be converted</param>
/// <returns>the time quantity representing the duration</returns>
template <class _Period1, class _Type> constexpr boost::units::quantity<boost::units::si::time> toBoostTime(std::chrono::duration<_Type, _Period1> in) {
    constexpr auto milli = boost::units::si::milli;
    constexpr auto sec   = boost::units::si::seconds;
    return boost::units::quantity<boost::units::si::time>(std::chrono::duration_cast<std::chrono::milliseconds>(in).count() * milli * sec);
}
jpo234
  • 419
  • 3
  • 9
  • It could help to show what you have done so far. It sounds like your mysterious `quantity – underscore_d Apr 09 '21 at 12:26
  • @underscore_d I have updated the question with my current conversion function. As for "mysterious quantity – jpo234 Apr 09 '21 at 12:35
  • 1
    There is no way to tell the compiler that there is an implicit conversion between the two quantities, you'd need to add conversion operators or constructors inside the class themselves. If you simply want to write code where you can accept both then you could use templated functions and/or use variant to accept either one, but there is no way to have your compiler automatically convert one from the other. – Holt Apr 09 '21 at 12:39
  • @Holt I understand that. I had hoped that there is some template magic that allows a user defined cast operator that works outside these classes. Both, boost and the C++ standard libraries can't be changed, after all. – jpo234 Apr 09 '21 at 12:49

0 Answers0