在C++中,各种数值类型的转化是C++编译过程中警告的主要来源,但是,很多时候,我们需要使用各种数值类型,例如我们用数组的某一位表示大小为对应序号的值,这种情况下,经常会涉及多种数值类型。根据C++ Programming Language中的建议,在数值类型转换时,使用narrow_cast来实现运行时安全,这里给出C++14版本的实现。

// there is no implicit conversion from Source to Target
template <typename Target, typename Source,
typename = std::enable_if_t<
!std::is_same<std::common_type_t<Target, Source>, std::decay_t<Target>>::value>>
inline Target narrow_cast(Source v)
{
static_assert(!std::is_reference<Target>::value, "The target couldn't be reference");
static_assert(std::is_arithmetic<Source>::value, "The parameter of narrow_cast should be arithmetic");
static_assert(std::is_arithmetic<Target>::value, "The return value of narrow_cast should be arithmetic"); // using Target_U = std::remove_reference_t<Target>;
// using Source_U = std::remove_reference_t<Source>; auto r = static_cast<Target>(v);
if (static_cast<Source>(r) != v)
throw std::runtime_error("narrow_cast<>() failed");
return r;
} // there is implicit conversion from Source to Target
template <typename Target, typename Source,
typename = std::enable_if_t<
std::is_same<std::common_type_t<Target, Source>, std::decay_t<Target>>::value>>
inline constexpr std::remove_reference_t<Source> narrow_cast(Source v)
{
static_assert(!std::is_reference<Target>::value, "The target couldn't be reference");
static_assert(std::is_arithmetic<Source>::value, "The parameter of narrow_cast should be arithmetic");
static_assert(std::is_arithmetic<Target>::value, "The return value of narrow_cast should be arithmetic"); return static_cast<Target>(v);
}

下面给出,使用Catch写的简单测试用例:

#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include <cmath> TEST_CASE("Test narrow_cast", "[narrow_cast]")
{
int i = ;
long long j = ;
long long& k = j;
REQUIRE(narrow_cast<long>(k) == );
REQUIRE(narrow_cast<long>(i) == );
long long very_big = pow(, );
bool exception = false;
try
{
narrow_cast<long>(very_big) == very_big;
}
catch (const std::runtime_error& error)
{
exception = true;
}
REQUIRE(exception);
//REQUIRE(narrow_cast<long&>(k) == 15);
//REQUIRE(narrow_cast<long&>(i) == 10);
}

测试可知,在转化的类型可以容纳时,narrow_cast可以正常运行,如果narrow_cast转化后的值与原值不同时,会抛出runtime_error的异常。

C++ Programming Language中的narrow_cast实现的更多相关文章

  1. C++ Programming Language中的Calculator源代码

    C++ Programming Language 4th中的Calculator源代码整理,因为在C++ Programming Language中,涉及了很多文件位置之类的变化,所以,这里只是其中的 ...

  2. 编程提取字符串"Java is a programming language"中的各个单词,并打印输出。

    import java.lang.String; import java.util.StringTokenizer; public class StringGetWord{ /* 编程提取字符串&qu ...

  3. iOS Swift-元组tuples(The Swift Programming Language)

    iOS Swift-元组tuples(The Swift Programming Language) 什么是元组? 元组(tuples)是把多个值组合成一个复合值,元组内的值可以使任意类型,并不要求是 ...

  4. iOS Swift-控制流(The Swift Programming Language)

    iOS Swift-控制流(The Swift Programming Language) for-in 在Swift中for循环我们可以省略传统oc笨拙的条件和循环变量的括号,但是语句体的大括号使我 ...

  5. The Swift Programming Language 中文翻译版(个人翻新随时跟新)

    The Swift Programming Language --lkvt 本人在2014年6月3日(北京时间)凌晨起来通过网络观看2014年WWDC 苹果公司的发布会有iOS8以及OS X 10.1 ...

  6. [iOS翻译]《The Swift Programming Language》系列:Welcome to Swift-01

    注:CocoaChina翻译小组已着手此书及相关资料的翻译,楼主也加入了,多人协作后的完整译本将很快让大家看到. 翻译群:291864979,想加入的同学请进此群哦.(本系列不再更新,但协作翻译的进度 ...

  7. the C programming language 阅读笔记1

    读了一遍著名的<the C programming language>,果然如听说的一样,讲解基础透彻,案例简单典型,确实自己C语言还有很多细节点不是很清楚. 总结一下阅读的收获(部分原书 ...

  8. Introduction to OOC Programming Language

    Introduction to OOC Programming Language 文/akisann @ cnblogs.com / zhaihj @ github.com 本文同时发布在github ...

  9. 不忘初心 --- 重读<<The C Programming Language>>

    这篇文章应该发布在好几年前,2011年计算机界大师Dennis Ritchie仙逝,那时对大师的映象还停留在大一刚学编程时:Unix的合作开发者,C语言的发明人.通过网上的纪念文章<<Un ...

随机推荐

  1. input type="tel" 输入框显示密文

    为了在移动端实现密码输入框且调起的键盘为数字键盘,可以用-webkit-text-security:disc;text-security:disc;属性来实现. 语法: text-security: ...

  2. MongoDB学习笔记——数据库的创建与初始

    Part1:MongoDB与SQL的概念对比 图片来源--菜鸟教程 Part2:MongoDB安装地址 直接下载地址:戳这里 备用地址:戳这里 通过备用地址(官网)下载时,要注意下面这个地方 Part ...

  3. php 添加环境变量

    1.php添加环境变量主要为了能在 cmd和软件的客户端用php来运行 首先我们要做的第一步: 添加环境变量(记住php.exe的路径,然后再环境变量中编辑path 多个用逗号分隔开,保存重启电脑) ...

  4. Starting MySQL....The server quit without updating PID file[失败]/lib/mysql/ip12189.pid). 错误一例

    [root@ip12189 etc]# service mysqld startStarting MySQL....The server quit without updating PID file[ ...

  5. win10下vs2015编译的程序如何运行在win7等系统(无需安装Redistributable)

    最近新写的程序要做beta测试,在做绿色版(免安装版)时遇到了问题,vs2015做的项目本以为像之前的vs版本一样把msvcrXXX.dll还有另外几个运行时库都放到exe旁边即可,然并卵...,在w ...

  6. liunx文件操作 文件压缩

    文件备份和压缩命令 在Linux中,常用的文件压缩工具有gzip,bzip2,zip. 'bzip2'是最理想的压缩工具,它提供了最大限度的压缩. 'zip'兼容好,windows也支持. bzip2 ...

  7. 二十三. Python基础(23)--经典类和新式类

    二十三. Python基础(23)--经典类和新式类 ●知识框架   ●接口类&抽象类的实现 # 接口类&抽象类的实现 #①抛出异常法 class Parent(object):    ...

  8. 使用md5加密算法完成简单的登录和注册功能

    原理: 登录:后端controller层获取到客户的密码,通过下面代码:new Sha256Hash(pwd).toHex();将密码转换成md5散列,生成一个新的字符串与数据库的值进行比对,根据不同 ...

  9. 有关Java垃圾回收的几个问题

    1.Java垃圾回收有什么目的?什么时候进行垃圾回收? 答:垃圾回收的目的是识别并丢弃应用中不再使用的对象以释放和重用资源. 2.System.gc()和Runtime.gc()会做什么事情? 答:这 ...

  10. Shell脚本的学习笔记一:变量

    三种变量: 局部变量:局部变量在脚本或命令中定义,仅在当前shell实例中有效,其他shell启动的程序不能访问局部变量. 环境变量:所有的程序,包括shell启动的程序,都能访问环境变量,有些程序需 ...