nholthaus / units

a compile-time, header-only, dimensional analysis and unit conversion library built on c++14 with no dependencies.
http://nholthaus.github.io/units/
MIT License
955 stars 135 forks source link

A variable holding a unit initialized with the unary operator "-" cannot be constexpr #283

Closed dsimonkay closed 2 years ago

dsimonkay commented 2 years ago

units version: 2.3.1 Compiler version: g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0

I want to define a variable holding a negative number with a unit. The variable needs to be constexpr, as it will appear in a static_assert later on.

The following code cannot be compiled:

#include "units.h"

int main()
{
    using units::literals::operator""_m;
    constexpr double whatever{-42.0_m};

    return 0;
}

The error:

units_bug.cpp:6:29: error: call to non-‘constexpr’ function ‘units::unit_t<Units, T, NonLinearScale> units::operator-(const units::unit_t<Units, T, NonLinearScale>&) [with Units = units::unit<std::ratio<1>, units::base_unit<std::ratio<1> > >; T = double; NonLinearScale = units::linear_scale]’
    6 |  constexpr double whatever{-42.0_m};
      |                             ^~~~~~

When adding constexpr to the definition of the unary operator: image

The code can be compiled.

JohelEGP commented 2 years ago

That was added in https://github.com/nholthaus/units/commit/37a3175abf87e2922c799d4baf49513ba0c4212c.

dsimonkay commented 2 years ago

Ahh, thank you, @JohelEGP ! I followed this specific link and missed to check the latest version.