2016-01-21 92 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) 
{ 
}