Created
October 6, 2022 17:58
-
-
Save k-128/580c4d0162e42a980c9532f53a381ac1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <chrono> | |
#include <ratio> | |
// m/s - SI derived unit | |
struct Speed | |
{ | |
long double value; | |
}; | |
// m - SI unit | |
template <class Ratio = std::ratio<1>> | |
struct Length | |
{ | |
unsigned long long value; | |
}; | |
auto operator ""_m(unsigned long long n) { return Length<>{n}; } | |
auto operator ""_km(unsigned long long n) { return Length<std::kilo>{n}; } | |
template <class Ratio, class Rep, class Period> | |
auto operator / ( | |
const Length<Ratio> &len, | |
const std::chrono::duration<Rep, Period> &dur) | |
{ | |
const auto len_ratio = static_cast<double>(Ratio::num) / Ratio::den; | |
const auto dur_sec = std::chrono::duration_cast<std::chrono::seconds>(dur); | |
return Speed{len_ratio * len.value / dur_sec.count()}; | |
} | |
int main() | |
{ | |
using namespace std::chrono_literals; | |
const Speed s1 = 30_m / 1s; | |
const Speed s2 = 108'000_m / 3'600s; | |
const Speed s3 = 108_km / 3'600s; | |
const Speed s4 = 108_km / 1h; | |
std::cout << "s1 = 30_m / 1s == " << s1.value << " m/s\n"; | |
std::cout << "s2 = 108'000_m / 3'600s == " << s2.value << " m/s\n"; | |
std::cout << "s3 = 108_km / 3'600s == " << s3.value << " m/s\n"; | |
std::cout << "s4 = 108_km / 1h == " << s4.value << " m/s\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment