get_unit_value在提升ODEINT中的作用

role of get_unit_value in boost ODEINT

本文关键字:ODEINT 作用 unit value get      更新时间:2023-10-16

在Boost库的以下代码中:

template<class T , class Enabler = void >
struct get_unit_value_impl
{
    static T value(const T &t)
    {
        return t;
    }
    typedef T result_type;
};

template<class T>
typename detail::get_unit_value_impl<T>::result_type get_unit_value(const T &t)
{
    return detail::get_unit_value_impl<T>::value(t);
}

get_unit_value的作用我不清楚。它做什么?我们传递一些东西给它,它返回相同的值。为什么要有人把它包成一个结构?除了减慢运行时间之外,它还能做什么吗?

这个代码是从这里调用的:

template< class Fac1 = double >
struct rel_error
{
    const Fac1 m_eps_abs , m_eps_rel , m_a_x , m_a_dxdt;
    rel_error( Fac1 eps_abs , Fac1 eps_rel , Fac1 a_x , Fac1 a_dxdt )
    : m_eps_abs( eps_abs ) , m_eps_rel( eps_rel ) , m_a_x( a_x ) , m_a_dxdt( a_dxdt ) { }

    template< class T1 , class T2 , class T3 >
    void operator()( T3 &t3 , const T1 &t1 , const T2 &t2 ) const
    {
        using std::abs;
        set_unit_value( t3 , abs( get_unit_value( t3 ) ) / ( m_eps_abs + m_eps_rel * ( m_a_x * abs( get_unit_value( t1 ) ) + m_a_dxdt * abs( get_unit_value( t2 ) ) ) ) );
    }
    typedef void result_type;
};

您忘记复制其中一个专业:

template<class T , class Enabler = void >
struct get_unit_value_impl
{
    static T value(const T &t)
    {
        return t;
    }
    typedef T result_type;
};
#ifndef __CUDACC__
template<class Unit , class T>
struct get_unit_value_impl< boost::units::quantity< Unit , T> >
{
    static T value( const boost::units::quantity< Unit , T> &t )
    {
        return t.value();
    }
    typedef T result_type;
};
#endif

get_unit_value()是取一个值并返回它,或者取一个boost::unit::quantity<Unit, T>并返回它的值。这样,调用者就不需要担心t是否只是int或更复杂的东西:

int x = 7;
quantity<length> L = 2.0*meters;
get_unit_value(x); // 7
get_unit_value(L); // 2.0