[英]How can std::reference_wrapper<int> use operator+= if std::reference_wrapper doesn't have operator+=?
Thank you all, I didn't even know about user-defined conversion function and how it works.谢谢大家,我什至不知道用户定义的转换 function 以及它是如何工作的。
Why is it possible to use std::reference_wrapper<int>::operator+=
, if such an operator does not exist, are there some implicit conversions?为什么可以使用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: Output:
3
4
To check that template works perfectly fine:要检查该模板是否工作正常:
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: Output:
4
Still works as before.仍然像以前一样工作。 How is that possible?这怎么可能?
Funny thing, that in auto d = b + c
, d
has an integer type.有趣的是,在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: Output:
int
It's because it's implicitly convertible to a reference to T
:这是因为它可以隐式转换为对T
的引用:
/* constexpr [c++20] */ operator T& () const noexcept;
In your case, it's implicitly convertible to an int&
.在您的情况下,它可以隐式转换为int&
。
This ability to be implicitly convertible to an int&
is also what would make it possible for you to define your function to take an int&
while passing it a std::reference_wrapper<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.