int main()
{
int x = 1;
auto ref = std::ref(x);
if (x < ref)
{
...
}
}
In the above code, I made an int variable and a reference_wrapper<int> variable, and then compared them, and it works well.
However, If I change the type int to string, It raises a compile error like this.
binary '<': 'std::string' does not define this operator or a conversion to a type acceptable to the predefined operator
I thought that reference_wrapper<string> would be implicitly converted to string, but wouldn't.
Are there any rules that prevent implicit conversion from reference_wrapper<string> to string?
std::reference_wrapper<>more or less supports only one operation: an implicit type conversion back to the original type (which isstd::stringin your case).But the problem is that the compiler has to know that an implicit conversion back to the original type is necessary.
That is why your example works with the built-in type
int, while not with the class template instantiationstd::stringof thebasic_stringclass template.The situation is similar to the below given example:
To solve this problem, we need to explicitly say that we want the original type, which we can do by using the
get()member function, as shown below: