How to cast the size_t to double or int C++

前端 未结 5 886
旧时难觅i
旧时难觅i 2020-12-25 09:48

My question is that

I have a size_t data, but now I want to convert it to double or int.

If I do something like

 size_t data = 99999999;
 in         


        
5条回答
  •  臣服心动
    2020-12-25 10:30

    You can use Boost numeric_cast.

    This throws an exception if the source value is out of range of the destination type, but it doesn't detect loss of precision when converting to double.

    Whatever function you use, though, you should decide what you want to happen in the case where the value in the size_t is greater than INT_MAX. If you want to detect it use numeric_cast or write your own code to check. If you somehow know that it cannot possibly happen then you could use static_cast to suppress the warning without the cost of a runtime check, but in most cases the cost doesn't matter anyway.

提交回复
热议问题