之间有什么区别
带有转发引用参数的功能模板
template<typename T>
void Universal_func(T && a)
{
}
和缩写功能模板吗?
void auto_fun(auto && a)
{
}
我可以用
Universal_func
替换auto_fun
吗? 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++的一部分,但是GCC的某些最新版本允许将此作为其对Concepts TS支持的扩展。
Concepts TS将此结构称为缩写函数模板(尽管以前称为泛型函数,我想这是一个泛型的术语)。规则可能太大而无法转储到此答案中,但是请查看this draft中的[dcl.fct]/16-19
中的所有详细信息。
第16段提供了不错的概述:
根据该草案中列出的规则,您的两个定义在功能上是等效的。
我们使用带有占位符参数的函数:
void auto_fun(auto && a)
{
}
并发明一个模板参数替换为:
template <typename T>
void auto_fun (T && a)
{
}
如您所见,它与不带占位符的函数具有相同的签名:
template <typename T>
void Universal_func(T && a)
{
}