48

我试图理解std::reference_wrapper

以下代码显示引用包装器的行为与引用不同。

#include <iostream>
#include <vector>
#include <functional>

int main()
{
    std::vector<int> numbers = {1, 3, 0, -8, 5, 3, 1};

    auto referenceWrapper = std::ref(numbers);
    std::vector<int>& reference = numbers;

    std::cout << reference[3]              << std::endl;
    std::cout << referenceWrapper.get()[3] << std::endl; 
              // I need to use get ^
              // otherwise does not compile.
    return 0;
}

如果我理解正确,隐式转换不适用于调用成员函数。这是一个固有的限制吗?我需要std::reference_wrapper::get经常使用吗?

另一种情况是这样的:

#include <iostream>
#include <functional>

int main()
{
    int a = 3;
    int b = 4;
    auto refa = std::ref(a);
    auto refb = std::ref(b);
    if (refa < refb)
        std::cout << "success" << std::endl;

    return 0;
}

这很好用,但是当我在main定义上方添加它时:

template <typename T>
bool operator < (T left, T right)
{
    return left.someMember();
}

编译器尝试实例化模板并忘记隐式转换和内置运算符。

这种行为是固有的,还是我误解了关于 std::reference_wrapper?

4

1 回答 1

52

Class std::reference_wrapper<T> implements an implicit converting operator to T&:

operator T& () const noexcept;

and a more explicit getter:

T& get() const noexcept;

The implicit operator is called when a T (or T&) is required. For instance

void f(some_type x);
// ...
std::reference_wrapper<some_type> x;
some_type y = x; // the implicit operator is called
f(x);            // the implicit operator is called and the result goes to f.

However, sometimes a T is not necessarily expected and, in this case, you must use get. This happens, mostly, in automatic type deduction contexts. For instance,

template <typename U>
g(U x);
// ...
std::reference_wrapper<some_type> x;
auto y = x; // the type of y is std::reference_wrapper<some_type>
g(x);       // U = std::reference_wrapper<some_type>

To get some_type instead of std::reference_wrapper<some_type> above you should do

auto y = x.get(); // the type of y is some_type
g(x.get());       // U = some_type

Alternativelly the last line above could be replaced by g<some_type>(x);. However, for templatized operators (e.g. ostream::operator <<()) I believe you can't explicit the type.

于 2013-08-08T14:11:59.740 回答