Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
679 views
in Technique[技术] by (71.8m points)

c++ - Issue with std::reference_wrapper

The issue is clear with the following code:

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

int main() {
  //std::vector<int> a, b;
  int a = 0, b = 0;
  auto refa = std::ref(a);
  auto refb = std::ref(b);
  std::cout << (refa < refb) << '
';
  return 0;
}

If I use the commented std::vector<int> a, b; instead of int a = 0, b = 0;, then the code does not compile on any of GCC 5.1, clang 3.6, or MSVC'13. In my opinion, std::reference_wrapper<std::vector<int>> is implicitly convertible to std::vector<int>& which is LessThanComparable, and thus it should be LessThanComparable itself. Could someone explain this to me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue is that the non-member operator< for std::vector is a function template:

template< class T, class Alloc >
bool operator<( const vector<T,Alloc>& lhs,
                const vector<T,Alloc>& rhs );

Implicit conversions are not considered when doing template type deduction here, [temp.arg.explicit] emphasis on if:

Implicit conversions (Clause 4) will be performed on a function argument to convert it to the type of the corresponding function parameter if the parameter type contains no template-parameters that participate in template argument deduction.

But in this case, the parameter type does participate in deduction. That's why it can't be found. Had we written our own non-template operator<:

bool operator<(const std::vector<int>& lhs, const std::vector<int>& rhs)
{
    return true;
}

Your code would work as expected. To use the generic one though, you will have to explicitly pull out the reference:

std::cout << (refa.get() < refb.get()) << '
';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...