C++核心准则T.44:使用函数模板推断类模板参数类型(如果可能)
T.44: Use function templates to deduce class template argument types (where feasible)
T.44:使用函数模板推断类模板参数类型(如果可能)
Reason(原因)
Writing the template argument types explicitly can be tedious and unnecessarily verbose.
显示输入模板参数类型冗长且无必要。
Example(示例)
tuple<int, string, double> t1 = {1, "Hamlet", 3.14}; // explicit type
auto t2 = make_tuple(1, "Ophelia"s, 3.14); // better; deduced type
Note the use of the s suffix to ensure that the string is a std::string, rather than a C-style string.
注意通过使用s后缀可以保证string是std::string而不是C风格字符串。
Note(注意)
Since you can trivially write a make_T function, so could the compiler. Thus, make_T functions might become redundant in the future.
你可以直接编写make_T函数,编译器也可以。因此make_T函数将来可能会变得多余。
Exception(例外)
Sometimes there isn't a good way of getting the template arguments deduced and sometimes, you want to specify the arguments explicitly:
有时,没有合适的方式实现模板参数推断,也有可能你希望显式定义参数类型。
vector<double> v = { 1, 2, 3, 7.9, 15.99 };
list<Record*> lst;
Note(注意)
Note that C++17 will make this rule redundant by allowing the template arguments to be deduced directly from constructor arguments: Template parameter deduction for constructors (Rev. 3). For example:
注意C++17将会令本规则多余,原因是C++17允许直接通过构造函数参数直接推断模板参数:构造函数的模板参数推断(Rev.3)。例如:
tuple t1 = {1, "Hamlet"s, 3.14}; // deduced: tuple<int, string, double>
Enforcement(实施建议)
Flag uses where an explicitly specialized type exactly matches the types of the arguments used.
标记显示定义的类型和实际使用的参数完全匹配的情况。
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t44-use-function-templates-to-deduce-class-template-argument-types-where-feasible
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法