[英]How can std::reference_wrapper<int> use operator+= if std::reference_wrapper doesn't have operator+=?
謝謝大家,我什至不知道用戶定義的轉換 function 以及它是如何工作的。
為什么可以使用std::reference_wrapper<int>::operator+=
,如果這樣的運算符不存在,是否有一些隱式轉換?
#include <iostream>
#include <functional>
#include <boost/type_index.hpp>
using boost::typeindex::type_id_with_cvr;
template <typename C>
void test(C c)
{
c += 1;
}
int main()
{
int a = 3;
test(a);
std::cout << a << std::endl;
test(std::ref(a));
std::cout << a << std::endl;
}
Output:
3
4
要檢查該模板是否工作正常:
void test_2(std::reference_wrapper<int> c)
{
c += 1;
}
int main()
{
int a = 3;
test_2(std::ref(a));
std::cout << a << std::endl;
}
Output:
4
仍然像以前一樣工作。 這怎么可能?
有趣的是,在auto d = b + c
中, d
有一個 integer 類型。
int main()
{
auto b = std::ref(a);
auto c = std::ref(a);
auto d = b + c;
std::cout << type_id_with_cvr<decltype(d)>).pretty_name() << std::endl;
}
Output:
int
這是因為它可以隱式轉換為對T
的引用:
/* constexpr [c++20] */ operator T& () const noexcept;
在您的情況下,它可以隱式轉換為int&
。
這種隱式轉換為int&
的能力也使您可以定義 function 以在傳遞std::reference_wrapper<int>
時采用int&
:
void test_2(int& c) // <--+
{ // |
c += 1; // |
} // |
int main() { // |
// ... // |
test_2(std::ref(a)); // >--+
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.