static_cast是否影响简单类型float的Boost

Does static_cast affect Boost for simple type float?

本文关键字:类型 float Boost 简单 影响 cast 是否 static      更新时间:2023-10-16

在Boost ODEINT库中,可以找到很多static_cast关键字,例如:

template<
class State ,
class Value = double ,
class Deriv = State ,
class Time = Value ,
class Algebra = typename algebra_dispatcher< State >::algebra_type ,
class Operations = typename operations_dispatcher< State >::operations_type ,
class Resizer = initially_resizer
>
class runge_kutta_dopri5: ....
{
    ...
    typedef typename stepper_base_type::value_type value_type;
    ...
    template< class System , class StateIn , class DerivIn , class StateOut , class DerivOut >
    void do_step_impl( System system , const StateIn &in , const DerivIn &dxdt_in , time_type t ,
        StateOut &out , DerivOut &dxdt_out , time_type dt )
    {
        const value_type a2 = static_cast<value_type> ( 1 ) / static_cast<value_type>( 5 );
        const value_type a3 = static_cast<value_type> ( 3 ) / static_cast<value_type> ( 10 );
        const value_type a4 = static_cast<value_type> ( 4 ) / static_cast<value_type> ( 5 );
        const value_type a5 = static_cast<value_type> ( 8 )/static_cast<value_type> ( 9 );
        .... 

其中value_type由模板决定。

我的问题是,如果value_type是像double一样的简单类型,那么static_cast<value_type> ( 5 )(double)5之间有什么区别吗?我想知道他们为什么用这样的铸件。如果value_typedouble&还是double&&,是相同的吗?

没有区别。

他们选择C++风格的演员阵容是因为他们更安全。

C样式强制转换可以执行任何重新解释强制转换,这甚至可能根本无法实现预期效果,当这种情况在Boost ODEINT 等高度geneirc库的内部悄悄发生时,这尤其危险

简单示例:

struct FixedPoint { 
    int x; 
    FixedPoint(int x):x(x) {}
    operator double() const { return x/10.0; }
};
// deep in the bowels of a library, this happens:
double test = static_cast<double>(FixedPoint(42)); // ok 4.2

但是,在其他地方,在一些不幸的人的代码库中:

struct FixedPoint { 
    int x; 
    FixedPoint(int x):x(x) {}
    double as_double() const { return x/10.0; }
};
// oops, good thing the compile catches this!
double test = static_cast<double>(FixedPoint(42)); // COMPILE ERROR

想象一下,如果写下了大屠杀

double test = (double) (FixedPoint(42)); // silent reinterpret_cast<double>

简而言之,在C++中,never编写C样式转换。这没用。

  • 常规强制转换与静态强制转换与动态强制转换
  • 应在何时使用static_cast、dynamic_cast、const_cast和relpret_cast