我想重载用户定义的文字,以便它允许执行一些物理计算,例如
auto force = 5_N; // force in newton
auto distance = 6.8_m; // distance in meters
auto resultingEnergy = force * distance; // expected result in joules
如何实现?
答案 0 :(得分:1)
您可以定义一些新类型(或使用上面提到的增强单位),
用户定义的解决方案可能类似于:
#define DECLARE_UNIT(UnitName) \
struct UnitName { \
UnitName(const long double val) noexcept : val_(val) {};\
long double val_ = 0.0; \
};
DECLARE_UNIT(Joule);
DECLARE_UNIT(Newton);
DECLARE_UNIT(Meters);
const Newton operator""_N(const long double n) noexcept {
return Newton(n);
}
const Meters operator""_m(const long double m) noexcept {
return Meters(m);
}
const Joule operator*(const Newton& newtons, const Meters& meters) noexcept {
return newtons.val_ * meters.val_;
}
int main() {
auto force = 5.0_N;
auto distance = 6.8_m;
auto energy = force * distance; // of Joule type
}