2016-01-21 225 views
8

什么是与转发引用参数缩函数模板对与转发参考PARAM函数模板

template<typename T> 
void Universal_func(T && a) 
{ 
} 

简称函数模板之间 函数模板的区别是什么?

void auto_fun(auto && a) 
{ 
} 

我可以代替Universal_funcauto_funUniversal_funcauto_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_funcauto_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 

有什么区别吗?标准说什么?

+3

带参数auto的函数不是标准的C++。 – 101010

+1

@ 101010它是C++ 14。 – Zereges

+5

@Zereges不,它不是。 Lambdas可以有'自动'参数IIRC,但功能肯定还没有。 – hvd

回答

10

auto函数参数不是标准C++的一部分,但是一些最新版本的GCC允许这个扩展作为对概念TS支持的一部分。

的概念TS指的是该构建体作为缩写函数模板(尽管它曾经被称为通用函数,我想是太一般的术语)。规则可能太大而无法转储到这个答案中,但请查看的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) 
{ 
}