繁体   English   中英

std::reference_wrapper 怎么能<int>如果 std::reference_wrapper 没有 operator+= 则使用 operator+=?</int>

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM