簡體   English   中英

顯式傳遞模板參數時,函數模板參數會丟失常量嗎?

[英]function template parameter loses const when template argument is explicity passed?

template <typename T>
void test(const T& x) {}

int a {};
int& ref = a;
const int& c_ref = a;

test(c_ref)  // T = int, x = const int&
test<int&>(ref); // T = int& , x = int&

為什么函數模板參數 x 失去了const限定符?

在顯式(非推導)實例化中

test<int&>(ref);

這是你得到的(理論)簽名

void test<int&>(const (int&)& x)

這表明const限定適用於整個(int&) ,而不僅僅是int const適用於剩下的東西,如果什么都沒有,它適用於正確的東西: int& ,但作為一個整體 - 在那里,它適用於& ,再次因為const適用於它左邊的東西。 但是沒有const引用(它們根本不能改變,即它們不能重新綁定), const被刪除,並且引用折疊規則將兩個&收縮為一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM