功能模板与自动关键字 [英] Function Templates vs. Auto Keyword

查看:171
本文介绍了功能模板与自动关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 11中的auto关键字可以代替功能模板和专业化功能吗?如果可以,使用模板函数和专业化方法比仅将函数参数键入为auto有什么优势?

Can the auto keyword in C++11 replace function templates and specializations? If yes, what are the advantages of using template functions and specializations over simply typing a function parameter as auto?

template <typename T>
void myFunction(T &arg)
{
    // ~
}

vs.

void myFunction(auto &arg)
{
    // ~
}

推荐答案

总而言之,auto不能用于省略函数参数的实际类型,因此请坚持使用函数模板和/或重载. auto用于合法地自动推断变量的类型:

In a nutshell, auto cannot be used in an effort to omit the actual types of function arguments, so stick with function templates and/or overloads. auto is legally used to automatically deduce the types of variables:

auto i=5;

但是要非常小心地理解以下两者之间的区别:

Be very careful to understand the difference between the following, however:

auto x=...
auto &x=...
const auto &x=...
auto *px=...; // vs auto px=... (They are equivalent assuming what is being 
              //                 assigned can be deduced to an actual pointer.)
// etc...

它也用于后缀返回类型:

It is also used for suffix return types:

template <typename T, typename U>
auto sum(const T &t, const U &u) -> decltype(t+u)
{
  return t+u;
}

这篇关于功能模板与自动关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆