static_cast是否影响简单类型float的Boost
Does static_cast affect Boost for simple type float?
在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_type
是double&
还是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
相关文章:
- 数组下标的类型"float*[float]"无效
- 错误:二进制'operator*' 'float'和'float[0]'类型的操作数无效
- 编译器给出错误:format 指定类型 'float *',但参数的类型'double' [-Wformat]
- OPENCL 警告:不兼容的指针类型将'float __global[16]'传递给类型为 '__global float4 的参数 *
- "错误:数组下标的无效类型'float [10001][float]'是什么意思?
- 将"float*"赋值为"float* [1000]"中的不兼容类型
- 数组类型 'float [size]'不可分配
- 错误:二进制'operator*' 'int [1]'和'float'类型的操作数无效
- 转换特征矩阵类型时,错误:在"float"之前预期主表达式
- 功能使用INT和Float类型作为C 中的参数过载
- tensorflow C API中的float数据类型
- 此背包代码显示浮点[float]无效类型错误.可能是什么原因
- typedef float _float32;的声明说明符中的两种或多种数据类型;
- 错误:C++ 中二进制"operator%"类型"float"和"int"的操作数无效
- 如何在C++中为integer、float和double数据类型同时重载运算符
- Waht [错误] 请求 memebr 'area' 在非类类型 'float' 中'r'是什么意思?
- Qt C++ - 不允许使用 QList<float**> 类型
- static_cast是否影响简单类型float的Boost
- 错误:类型 " float(*)[1] " 的参数与类型 " float** " 的参数不兼容
- (程序设计语言C/C++)中的格式值类型float