Repository navigation
Expand file tree
/
Copy pathexpno 11.cpp
More file actions
67 lines (58 loc) · 1.47 KB
/
Copy pathexpno 11.cpp
File metadata and controls
67 lines (58 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
using namespace std;
// Unit definitions
struct Meter
{
static constexpr double factor = 1.0;
};
struct Kilometer
{
static constexpr double factor = 1000.0;
};
struct Centimeter
{
static constexpr double factor = 0.01;
};
// Template class for type-safe quantity
template <typename Unit>
class Quantity
{
private:
double value;
public:
constexpr Quantity(double v) : value(v) {}
constexpr double getValue() const
{
return value;
}
};
// Template conversion function
template <typename ToUnit, typename FromUnit>
constexpr Quantity<ToUnit> convert(
const Quantity<FromUnit> &quantity)
{
// Convert source unit to base unit (meter)
double baseValue =
quantity.getValue() * FromUnit::factor;
// Convert base unit to target unit
double convertedValue =
baseValue / ToUnit::factor;
return Quantity<ToUnit>(convertedValue);
}
int main()
{
// Create quantity in meters
constexpr Quantity<Meter> distance(5000);
// Compile-time conversion
constexpr auto km =
convert<Kilometer>(distance);
constexpr auto cm =
convert<Centimeter>(distance);
cout << "Distance in Meters: "
<< distance.getValue() << " m" << endl;
cout << "Distance in Kilometers: "
<< km.getValue() << " km" << endl;
cout << "Distance in Centimeters: "
<< cm.getValue() << " cm" << endl;
return 0;
}