从“xxxx”到“yyyy”的转换,可能会丢失数据,抑制? [英] Conversion from 'xxxx' to 'yyyy', possible loss of data, suppression?

查看:132
本文介绍了从“xxxx”到“yyyy”的转换,可能会丢失数据,抑制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候,我有警告,从较长的类型转换为较小的类型,例如:

  void f i)// f  - 接受任何数字类型
//小于std :: vector<> :: size_type
{}

std :: vector< some_type> v;
..
f(v.size());

通常我使用下列解决方案之一:

  assert(v.size()< = std :: numeric_limits< unsigned short> :: max()); 
f(static_cast< unsigned short>(v.size()));

  f(boost :: numeric_cast< unsigned short>(v.size())); 

但是在我现在的工作,提升没有使用,从上个月以来的断言是不允许的。



您知道什么其他安全方法来抑制此警告?

有什么陷阱?



PS:
不一定可以更改f的签名,有时候实际上应该接受小数字类型。 / p>

已编辑:
我想尽可能安全地进行转换。

解决方案

为什么要放在第一位?向量的大小通常是无符号整数。如果可能,我会说更新函数签名。


Sometimes I've got warnings with conversion from a longer type to a smaller type e.g.:

void f( unsigned short i ) // f - accept any numeric type
                           // smaller than std::vector<>::size_type
{}

std::vector < some_type > v;
..
f ( v.size() );

Usually I was using one of next solutions:

assert( v.size() <= std::numeric_limits< unsigned short >::max() );
f( static_cast< unsigned short >( v.size() ) );

or

f( boost::numeric_cast<  unsigned short >( v.size() ) );

But on my present work boost not used and from last month asserts are disallowed.

What other safe ways you know for suppress this warning?
Any pitfalls in discribed ways?

PS: It is not always possible to change the signature of f, also sometimes really should accept small numeric type.

EDITED: I want to make conversion as safe as possible.

解决方案

Why cast in the first place? The vector's size is typically an unsigned integer. If possible, I'd say update the function signature. Warnings are not meant to be suppressed, rather addressed.

这篇关于从“xxxx”到“yyyy”的转换,可能会丢失数据,抑制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆