【发布时间】:2016-04-27 09:45:59
【问题描述】:
两者有什么区别 带有转发参考参数的函数模板
template<typename T>
void Universal_func(T && a)
{
}
和缩写函数模板?
void auto_fun(auto && a)
{
}
我可以用auto_fun 替换Universal_func 吗? Universal_func 是 auto_fun 还是相等的?
我已经测试了下面的程序。好像两者都是一样的。
template<typename T>
void Universal_func(T && a)
{
}
void auto_fun(auto && a)
{
}
int main()
{
int i;
const int const_i = 0;
const int const_ref =const_i;
//forwarding reference template function example
Universal_func(1); //call void Universal_func<int>(int&&)
Universal_func(i);//call void Universal_func<int&>(int&):
Universal_func(const_i); //call void Universal_func<int const&>(int const&)
Universal_func(const_ref);//call void Universal_func<int const&>(int const&)
//auto calls
auto_fun(1); //call void auto_fun<int>(int&&)
auto_fun(i);//call void auto_fun<int&>(int&):
auto_fun(const_i); //call void auto_fun<int const&>(int const&)
auto_fun(const_ref);//call void auto_fun<int const&>(int const&)
return 0;
}
Universal_func 和auto_fun 推导和扩展为类似的功能。
void Universal_func<int>(int&&):
pushq %rbp
movq %rsp, %rbp
movq %rdi, -8(%rbp)
nop
popq %rbp
ret
void Universal_func<int&>(int&):
pushq %rbp
movq %rsp, %rbp
movq %rdi, -8(%rbp)
nop
popq %rbp
ret
void Universal_func<int const&>(int const&):
pushq %rbp
movq %rsp, %rbp
movq %rdi, -8(%rbp)
nop
popq %rbp
ret
void auto_fun<int>(int&&):
pushq %rbp
movq %rsp, %rbp
movq %rdi, -8(%rbp)
nop
popq %rbp
ret
void auto_fun<int&>(int&):
pushq %rbp
movq %rsp, %rbp
movq %rdi, -8(%rbp)
nop
popq %rbp
ret
void auto_fun<int const&>(int const&):
pushq %rbp
movq %rsp, %rbp
movq %rdi, -8(%rbp)
nop
popq %rbp
ret
有什么不同吗?标准是怎么说的?
【问题讨论】:
-
带参数 auto 的函数不是标准 C++。
-
@Zereges 不,不是。 Lambda 可以有
auto参数 IIRC,但函数肯定还没有。 -
@Zereges 我认为在 C++14 中,只有 lambda 参数列表可以使用
auto。其他功能处于Concepts TS阶段。 -
它不是 C++14 主线的一部分。带有 auto 的函数可能会在 C++17 中作为“通用函数”添加。
-
它被 GCC 接受为扩展(不使用 -pentatic),它不是标准的 C++,至少现在还不是。
标签: c++ templates c++14 type-deduction template-argument-deduction