函数模板与转发引用参数的区别是什么?
template<typename T>
void Universal_func(T && a)
{
}和缩写函数模板
void auto_fun(auto && a)
{
}我可以用Universal_func代替auto_fun吗?Universal_func是auto_fun的a还是它们是相等的?
我已经测试了下面的程序。看来两者是一样的。
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有什么不同吗?标准怎么说?
发布于 2016-01-21 08:54:07
函数参数中的auto还不是标准C++的一部分,但是一些最新版本的GCC允许将此作为扩展,作为对概念TS的支持的一部分。
概念TS将此构造称为缩写函数模板(虽然它以前被称为泛型函数,但我认为它过于泛型)。这些规则可能太大了,无法放入这个答案,但是看看[dcl.fct]/16-19在this draft中的所有血淋淋的细节。
第16段提供了一个像样的概述:
缩写函数模板是一个函数声明,其参数类型列表包括一个或多个占位符(7.1.6.4)。缩写函数模板相当于函数模板(14.6.6),其模板参数列表包括一个已发明的模板参数,用于参数声明子句中的占位符,按照以下规则按出现顺序排列。注意:当声明的类型包含占位符时,模板参数也用于推断变量的类型或函数的返回类型(7.1.6.4.1)。-尾注
根据该草案中规定的规则,您的两个定义在功能上是等价的。
我们使用带有占位符参数的函数:
void auto_fun(auto && a)
{
}并创建一个模板参数,将其替换为:
template <typename T>
void auto_fun (T && a)
{
}如您所见,这与没有占位符的函数具有相同的签名:
template <typename T>
void Universal_func(T && a)
{
}https://stackoverflow.com/questions/34918814
复制相似问题