c++模板元编程学习笔记(二)——量纲框架

本文介绍了一种使用模板元编程来定义和操作物理量纲的方法。通过定义基本量纲如质量、长度、时间等,并利用模板类实现复合量纲如速度、加速度等。文章还展示了如何对这些量纲进行加法、减法、乘法和除法运算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基本量纲

typedef mpl::vector_c<int, 1, 0, 0, 0, 0, 0, 0> mass; // 质量
typedef mpl::vector_c<int, 0, 1, 0, 0, 0, 0, 0> length; //长度
typedef mpl::vector_c<int, 0, 0, 1, 0, 0, 0, 0> time; //时间
typedef mpl::vector_c<int, 0, 0, 0, 1, 0, 0, 0> charge; // 电荷
typedef mpl::vector_c<int, 0, 0, 0, 0, 1, 0, 0> temperature; // 温度
typedef mpl::vector_c<int, 0, 0, 0, 0, 0, 1, 0> intensity; // 密度
typedef mpl::vector_c<int, 0, 0, 0, 0, 0, 0, 1> amount_of_substance; // 量

复合量纲

typedef mpl::vector_c<int, 0, 1, -1, 0, 0, 0, 0> velocity; //速度
typedef mpl::vector_c<int, 0, 1, -2, 0, 0, 0, 0> acceleration; //加速度
typedef mpl::vector_c<int, 1, 1, -1, 0, 0, 0, 0> momentum; //动量
typedef mpl::vector_c<int, 1, 1, -2, 0, 0, 0, 0> force; //力

类型定义

template <typename T, typename Dimensions>
class quantity
{
public:
	explicit quantity(T x)
		: m_value(x)
	{}

	template <typename OtherDimensions>
	quantity(quantity<T, OtherDimensions> const& rhs)
		: m_value(rhs.value())
	{
		static_assert(mpl::equal<Dimensions, OtherDimensions>::type::value, "type not equal");
	}

	T value() const { return m_value; }
private:
	T m_value;
};

量纲的四则运算

// 加法
template <typename T, typename D1, typename D2>
quantity<T,D>
operator+(quantity<T, D1> x, quantity<T, D2> y)
{
	static_assert(mpl::equal<D1, D2>::type::value, "type not equal");
	return quantity<T, D1>(x.value() + y.value());
}

// 减法
template <typename T, typename D1,typename D2 >
quantity<T, D>
operator-(quantity<T, D1> x, quantity<T, D2> y)
{
	static_assert(mpl::equal<D1, D2>::type::value, "type not equal");
	return quantity<T, D1>(x.value() - y.value());
}

// 乘法
template <typename T, typename D1, typename D2>
quantity<T,typename mpl::transform<D1,D2,mpl::plus<mpl::_1, mpl::_2>>::type>
operator*(quantity<T, D1> x, quantity<T, D2> y)
{
	typedef typename mpl::transform<D1, D2, mpl::plus<mpl::_1, mpl::_2>>::type dim;
	return quantity<T, dim>(x.value() * y.value());
}

// 除法
template <typename T, typename D1, typename D2>
quantity<T, typename mpl::transform<D1, D2, mpl::minus<mpl::_1, mpl::_2>>::type>
operator/(quantity<T, D1> x, quantity<T, D2> y)
{
	typedef typename mpl::transform<D1, D2, mpl::minus<mpl::_1, mpl::_2>>::type dim;
	return quantity<T, dim>(x.value() / y.value());
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值