C++怎么使用函数模板推断类模板参数类型

发布时间:2021-11-24 11:05:00 作者:iii
来源:亿速云 阅读:140

这篇文章主要讲解了“C++怎么使用函数模板推断类模板参数类型”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C++怎么使用函数模板推断类模板参数类型”吧!

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.

标记显示定义的类型和实际使用的参数完全匹配的情况。

感谢各位的阅读,以上就是“C++怎么使用函数模板推断类模板参数类型”的内容了,经过本文的学习后,相信大家对C++怎么使用函数模板推断类模板参数类型这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. C++函数模板举例
  2. c++类模板深度剖析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:C++怎么实现模板参数最少是正规或半正规的

下一篇:JSON中如何将OC的数组转化成OC格式的字符串

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》