mpusz / mp-units

The quantities and units library for C++
https://mpusz.github.io/mp-units/
MIT License
998 stars 79 forks source link

How to use other numeric types? #467

Closed ooxi closed 1 year ago

ooxi commented 1 year ago

We would like to use mp-units in our embedded product with fixed point math:

#include <mp-units/systems/si/si.h>
#include <https://raw.githubusercontent.com/eteran/cpp-utilities/master/fixed/include/cpp-utilities/fixed.h>

using namespace mp_units::si::unit_symbols;

static_assert(numeric::fixed<16, 16>{1} * h == numeric::fixed<16, 16>{3600} * s);

However, it seems like operator overloads are missing (see Compiler Explorer):

<source>:6:41: error: no match for 'operator*' (operand types are 'numeric::fixed<16, 16>' and 'const mp_units::si::hour')
    6 | static_assert(numeric::fixed<16, 16>{1} * h == numeric::fixed<16, 16>{3600} * s);
      |                        ~~~~~~~~~~~~~~~~ ^ ~
      |                        |                  |
      |                        |                  const mp_units::si::hour
      |                        numeric::fixed<16, 16>
In file included from <source>:2:

I therefore have the following questions:

  1. Is support for user defined numeric types present/planned?
  2. If yes, how to bootstrap a new numeric type?
ooxi commented 1 year ago

I was most likely looking for Custom Representation Types. Will reopen this ticket if my experiments fail.

mpusz commented 1 year ago

Hi, sure, custom representation types are supported. There are a few examples in the repository already:

For the last few days, I have been working on improving the concepts and requirements for representation types, but it will take me a while because I want to improve support for vector and tensor quantities as well.

mpusz commented 1 year ago

This is how you can make your example work: https://godbolt.org/z/M8E49Po3P

mpusz commented 1 year ago

Please note that there is no documentation (besides README) for V2 for now. I will be working on it in the upcoming weeks.

ooxi commented 1 year ago

Thank you very much @mpusz!

template<size_t I, size_t F>
inline constexpr bool mp_units::is_scalar<numeric::fixed<I, F>> = true;

This was what I was missing in order to make it work without too much clutter.

mpusz commented 1 year ago

In case you would also like to use this representation type with vector or tensor quantities, you should also specialize traits for them.