函数模板与自动关键字 [英] Function Templates vs. Auto Keyword
问题描述
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)
{
// ~
}
对比
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屋!