[英]What is the crux of std::reference_wrapper implementation for the only purpose of makin std::ref work?
[英]How do reference_wrapper and std::ref work?
我試圖了解std :: ref的工作原理。
#include <functional>
#include <iostream>
template <class C>
void func(C c){
c += 1;
}
int main(){
int x{3};
std::cout << x << std::endl;
func(x);
std::cout << x << std::endl;
func(std::ref(x));
std::cout << x << std::endl;
}
Output : 3 3 4
在上面的代碼中,我認為第三個函數調用的模板參數C
被實例化為std::reference_wrapper<int>
。 在閱讀引用時 ,我注意到std::reference_wrapper<int>
沒有+=
運算符。 那么, c += 1;
是多少c += 1;
有效?
怎么是
c += 1;
有效?
因為reference_wrapper<int>
可以通過其轉換運算符隱式轉換為int&
; 如果操作數類型本身沒有合適的重載,則考慮操作數的隱式轉換。
std::reference_wrapper<T>
有一個到T&
的轉換運算符 。 這意味着std :: reference_wrapper可以在您的示例中隱式轉換為int&
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.