|
3.1节是以一个"量纲分析"的程序作为示例来讲解的,我整理了一下,把代码发上来了
#include <boost/mpl/vector_c.hpp>
#include <boost/mpl/int.hpp>
#include <boost/static_assert.hpp>
#include <boost/mpl/plus.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/transform.hpp>
#include<boost/mpl/placeholders.hpp>
namespace mpl = boost::mpl;
using namespace mpl::placeholders;
template <class T, class Dimensions>
struct quantity
{
explicit quantity(T x)
: m_value(x)
{}
// converting constructor
template <class OtherDimensions>
quantity(quantity<T,OtherDimensions> const& rhs)
: m_value(rhs.value())
{
}
T value() const { return m_value; }
private:
T m_value;
};
template <class T, class D1, class D2>
quantity<
T
, typename mpl::transform<D1,D2,mpl::minus<_1,_2> >::type
>
operator/(quantity<T,D1> x, quantity<T,D2> y)
{
typedef typename
mpl::transform<D1,D2,mpl::minus<_1,_2> >::type dim;
return quantity<T,dim>( x.value() / y.value() );
}
template <class T, class D1, class D2>
quantity<
T
, typename mpl::transform<D1,D2,mpl::plus<_1,_2> >::type
>
operator*(quantity<T,D1> x, quantity<T,D2> y)
{
typedef typename
mpl::transform<D1,D2,mpl::plus<_1,_2> >::type dim;
return quantity<T,dim>( x.value() * y.value() );
}
template <class T,class D>
quantity<T,D> operator+(quantity<T,D> x,quantity<T,D> y)
{
return quantity<T,D>(x.value()-y.value());
}
template <class T,class D>
quantity<T,D> operator-(quantity<T,D> x,quantity<T,D> y)
{
return quantity<T,D>(x.value()-y.value());
}
int _tmain(int argc, _TCHAR* argv[])
{
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; // or position
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> angle;
typedef mpl::vector_c<int,0,1,-1,0,0,0,0> velocity; // l/t
typedef mpl::vector_c<int,0,1,-2,0,0,0,0> acceleration; // l/(t2)
typedef mpl::vector_c<int,1,1,-1,0,0,0,0> momentum; // ml/t
typedef mpl::vector_c<int,1,1,-2,0,0,0,0> force; // ml/(t2)
quantity<float,force> f(2.0f);
quantity<float,acceleration> a(1.0f);
quantity<float,mass> m(2.0f);
quantity<float,mass> m2=f/a;
std::cout<<typeid(m2).name()<<"\n";
std::cout<<typeid(m).name()<<"\n";
return 0;
} |
|