[英]What's the difference between const_iterator<T> and iterator<const T>?
[英]What's the difference between const T & and T & in template deduction
#for example:
#1:
template <typename T>
void func(T &) {}
int a;
const int b;
func(a); // T -> int
func(b); // T -> const int
func(5); // wrong. 5 is a right value
#2:
template <typename T>
void func(const T &) {}
int a;
const int b;
func(a); // T -> int
func(b); // T -> int
func(5); // T -> int
#3
template <typename T>
void func(T &&) {}
func(5); // T -> int
我的問題是:
為什么第一個代碼不起作用,為什么這與左/右值有關;
為什么3'中的T
不是const int
為什么第1個代碼不起作用;為什么這與左/右值有關;
對於第一種情況, T
將推導為int
,然后參數類型為int &
,這是對非const的左值引用。 5
是一個rvalue,它不能綁定到非const的lvalue-reference,然后調用失敗。
對於第二種情況,函數的參數類型是const int &
,即對const的lvalue-reference,它可以綁定到像5
這樣的rvalue。
為什么3'中的
T
不是const int
模板參數推導不會增加 const
如果參數類型不是const
。 5
是int
類型(它是一個rvalue),但它的類型不是const int
。
在另一方面,我們有轉發參考來處理左值/右值。 例如
template <typename T>
void func(T &&) {}
int a;
const int b;
func(a); // T -> int&; parameter type -> int&
func(b); // T -> const int&; parameter type -> const int&
func(5); // Fine. T -> int; paramter type -> int&&
這一切都歸結為表達式的屬性。 5
是表達式。 它有一個類型和一個值類別。 5
的類型是int
,而不是const int
,只是普通的int
。 它是一個prvalue(這是值類別)。
因此,當推導T&
5
,該類型只能推導為int
。 這意味着合成函數接受int&
,它不能綁定到rvalue。
當推導出T const&
,類型T
仍然只能在模板參數推導的適當規定下推導為int
。 但是現在合成函數接受一個int const&
,並且可以很好地綁定到右值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.