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

面向对象思考

共 2035字,需浏览 5分钟

 ·

2020-09-10 12:42

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 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 v = { 1, 2, 3, 7.9, 15.99 };
list 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

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


新书介绍

《实战Python设计模式》是作者最近出版的新书,拜托多多关注!

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。




觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!



浏览 18
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报