本文介绍了隐式模板推导指南可以推导引用类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用gcc7测试C ++ 17演绎指南行为时,我发现此示例失败:

While testing C++17 deduction guide behaviour with gcc7, I found that this example fails:

template<class T>
struct S{
  S(T&& v){}
};
int i=10;
auto v = S(i);

根据我从,我认为 v 的类型应为 S< ; int& 。但是,gcc7不会编译该代码,抱怨 int& 不能绑定到 int&&

According to what I have read from cpp reference, I thought v should be of type S<int &>. Nevertheless gcc7 does not compile this code complaining that a int& can not be bound to a int && (the universal reference mechanism fails).

所以我的问题是:


  1. gcc7是否应推导 v S< int&> 类型?

在工作草案标准中描述了自动扣除指南?

Where are described automatic deduction guide in the working draft standard?


推荐答案

是:

我们的集合包括:

template <class T> // <-- the template parameters come from the class template
S<T>               // <-- the return type is the class template specialization
foo(T&& );         // <-- the types of the parameters are those of the constructor

通常,这涉及模板推导。 但是来自 :

We perform overload resolution as usual, which involves template deduction. But from [temp.deduct.call]:

因此,该 T& 不是是转发参考。它是对 T 的右值引用。因此,对左值(在我们的例子中为 S(i))进行推导失败。 gcc在这里拒绝您的代码是正确的。

Hence, this T&& is not a forwarding reference. It is an rvalue reference to T. So deduction against an lvalue (in our case, S(i)) fails. gcc is correct to reject your code here.

如果您希望类模板参数用作转发参考,则需要添加一个推导指南:

If you want the class template parameter to function as a forwarding reference, you will need to add a deduction guide:

template <class T> S(T&& ) -> S<T>;

这篇关于隐式模板推导指南可以推导引用类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 00:31
查看更多