问题与std :: reference

编程入门 行业动态 更新时间:2024-10-27 23:30:40
本文介绍了问题与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) << '\n'; return 0; }

如果我使用注释的 std :: vector< int> a,b; 而不是 int a = 0,b = 0; ,那么代码不能在GCC 5.1,clang 3.6 ,或MSVC'13。在我看来, std :: reference_wrapper< std :: vector< int>> 可隐式转换为 std :: vector< int& 这是LessThanComparable,因此它应该是LessThanComparable本身。

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?

推荐答案

问题是非成员 operator std :: vector 是一个函数模板:

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 );

在执行模板类型扣除时,隐式转换不 .arg.explicit]强调if:

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

隐式转换(第4条)将对函数参数执行,以将其转换为类型对应的函数参数 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.

但在这种情况下,参数类型确实参与了扣除。这就是为什么它不能找到。如果我们写我们自己的非 -template 运算符

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()) << '\n';

更多推荐

问题与std :: reference

本文发布于:2023-08-04 17:26:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1298210.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:std   reference

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!