Skip to content

Commit 534be22

Browse files
committed
[math] Add chrono units for template parameters
1 parent 8f880ee commit 534be22

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/modm/math/units.hpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
#include <stdint.h>
1616
#include <modm/architecture/utils.hpp>
17+
#include <chrono>
1718

1819
#ifdef __DOXYGEN__
1920

@@ -38,6 +39,10 @@ namespace modm
3839

3940
using percent_t = float;
4041
template<typename T> constexpr percent_t pct(T value);
42+
43+
using seconds_t = std::chrono::seconds;
44+
using milliseconds_t = std::chrono::milliseconds;
45+
using microseconds_t = std::chrono::microseconds;
4146
/// @}
4247

4348
namespace literals
@@ -76,6 +81,15 @@ namespace literals { \
7681
constexpr MODM_CONCAT(name, _t) MODM_CONCAT(operator""_M, symbol)(long double value) { return MODM_CONCAT(M, symbol)(value); } \
7782
}
7883

84+
#define MODM_UNITS_TIME_DEFINITION(type) \
85+
struct MODM_CONCAT(type, _t) { \
86+
template< class Rep, class Period > \
87+
constexpr MODM_CONCAT(type, _t)(std::chrono::duration<Rep, Period> duration) \
88+
: count_{std::chrono::duration_cast<std::chrono::type>(duration).count()} {} \
89+
std::chrono::type::rep count_; \
90+
constexpr std::chrono::type::rep count() const { return count_; } \
91+
};
92+
7993
namespace modm
8094
{
8195

@@ -92,6 +106,11 @@ namespace literals
92106
constexpr percent_t operator""_pct(long double value) { return pct(value); }
93107
constexpr percent_t operator""_pct(unsigned long long int value) { return pct(value); }
94108
}
109+
110+
MODM_UNITS_TIME_DEFINITION(seconds)
111+
MODM_UNITS_TIME_DEFINITION(milliseconds)
112+
MODM_UNITS_TIME_DEFINITION(microseconds)
113+
95114
using namespace ::modm::literals;
96115
}
97116

src/modm/math/units.lb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,24 @@ percent_t tolerance = modm::pct(10);
6060
```
6161
6262
63+
## Time
64+
65+
Simplified types allow passing `std::chrono::duration` values as template
66+
parameters:
67+
68+
```cpp
69+
seconds_t duration = 10s;
70+
milliseconds_t duration = 10ms;
71+
microseconds_t duration = 10us;
72+
73+
auto count = duration.count();
74+
75+
template< milliseconds_t period >
76+
void setPeriod()
77+
{
78+
auto seconds = 1000.0 / period.count();
79+
}
80+
```
6381
"""
6482

6583
def prepare(module, options):

0 commit comments

Comments
 (0)