Skip to content

Instantly share code, notes, and snippets.

@tlehman
Created October 30, 2018 21:49
Show Gist options
  • Save tlehman/d1faa9f2bd3c8270f04cc0746c200ece to your computer and use it in GitHub Desktop.
Save tlehman/d1faa9f2bd3c8270f04cc0746c200ece to your computer and use it in GitHub Desktop.
Units in C++ using user-defined literals
// Units in C++ with user-defined literals
// g++ units.cpp -std=c++11 && ./a.out
#include <assert.h>
#include <iostream>
using namespace std;
long double operator "" _km(long double x) {
return 0.6213725 * x;
}
// 🇺🇸
long double operator "" _mi(long double x) {
return x;
}
int main() {
long double delta = 0.00001;
assert((1.60934_km - 1.0_mi) < delta);
cout << "1.60934_km ≈ 1.0_mi" << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment