謝謝大家,我什至不知道用戶定義的轉換函式及其作業原理。
為什么可以使用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;
}
輸出:
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;
}
輸出:
4
仍然像以前一樣作業。這怎么可能?
有趣的是, inauto d = b c有d一個整數型別。
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;
}
輸出:
int
uj5u.com熱心網友回復:
這是因為它可以隱式轉換為對 的參考T:
/* constexpr [c 20] */ operator T& () const noexcept;
在您的情況下,它可以隱式轉換為int&.
這種隱式轉換為 an 的能力int&也使您可以定義函式以將其int&傳遞給 a std::reference_wrapper<int>:
void test_2(int& c) // <--
{ // |
c = 1; // |
} // |
int main() { // |
// ... // |
test_2(std::ref(a)); // >--
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/513379.html
標籤:C c 11性病
