前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则T.44:使用函数模板推断类模板参数类型(如果可能)

C++核心准则T.44:使用函数模板推断类模板参数类型(如果可能)

作者头像
面向对象思考
发布2020-09-10 10:44:15
1.1K0
发布2020-09-10 10:44:15
举报

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(示例)

代码语言:javascript
复制
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:

有时,没有合适的方式实现模板参数推断,也有可能你希望显式定义参数类型。

代码语言:javascript
复制
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)。例如:

代码语言:javascript
复制
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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-09-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • T.44: Use function templates to deduce class template argument types (where feasible)
  • Reason(原因)
    • Note(注意)
      • Enforcement(实施建议)
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档