Boost logo

Boost Users :

Subject: [Boost-users] Boost.Units: Is it possible to convert on assignment without casting?
From: Carel Combrink (carel.combrink_at_[hidden])
Date: 2019-01-14 08:50:41


Hi.

I have two unit quantities defined as follow:
static const auto Hz = boost::units::si::hertz;
static const auto KHz = boost::units::si::kilo * Hz;
using Hertz = boost::units::quantity<decltype( Hz ), double>;
using Kilohertz = boost::units::quantity<decltype( KHz ), double>;

Assigning one type to another does not compile:
Kilohertz freqKhz = Kilohertz::from_value( 1.234 );
Hertz freqHz = freqKhz;
>>> error: conversion from 'Kilohertz {aka boost::units::quantity<...>,
double>}' to non-scalar type 'Hertz {aka boost::units::quantity<...>,
double>}' requested [1]

Is this possible, should it be enabled or is it not supported?
I am using boost 01.67, Mingw 5.3 and MSVC 2017 (C++14)

The following options work as expected:
Hertz freq1 = static_cast<Hertz>( freqKhz );
Hertz freq2 = Hertz( freqKhz );

But this adds a bit more code to maintain and keep in sync, one thing one
tries to avoid when using the library since one needs to keep the LHS and
the RHS of the opertor= in sync.

PS: The chrono library allows this type of conversion given there is no
information lost (but for double as storage types this should not be the
case)
std::chrono::seconds sec = std::chrono::seconds { 10 };
std::chrono::nanoseconds nsec = sec;

[1] https://gcc.godbolt.org/z/0sTHQQ

Regards,
Carel



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net