C++11 是否可以使用用户定义的文字实现SI系统的派生单位?
我想重载用户定义的文本,以便它能够执行一些物理计算,例如C++11 是否可以使用用户定义的文字实现SI系统的派生单位?,c++11,user-defined-literals,C++11,User Defined Literals,我想重载用户定义的文本,以便它能够执行一些物理计算,例如 auto force = 5_N; // force in newton auto distance = 6.8_m; // distance in meters auto resultingEnergy = force * distance; // expected result in joules 如何实现这一点?您可以定义一些新类型(或使用上述增压装置) 用户定义的解决方案可以类似于: #define
auto force = 5_N; // force in newton
auto distance = 6.8_m; // distance in meters
auto resultingEnergy = force * distance; // expected result in joules
如何实现这一点?您可以定义一些新类型(或使用上述增压装置) 用户定义的解决方案可以类似于:
#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
}
对于值(或新类型)和重载运算符,需要使用强typedef。文字仅产生某些给定类型的值,这是一种语法糖。您可以查看灵感,基本上让用户定义的文字返回适当的Boost.Units类型。