推导中参考值与参考值之间的差异 [英] Difference between references and values in deduction guides

查看:127
本文介绍了推导中参考值与参考值之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑类型A:

template <typename T, size_t N>
struct A
{
    T arr[N];
};

C ++ 17用户定义的演绎指南

Is there any difference between C++17 user-defined deduction guides

template <typename T, typename ... Ts>
A(const T&, const Ts& ...) -> A<T, 1 + sizeof...(Ts)>;

template <typename T, typename ... Ts>
A(T, Ts ...) -> A<T, 1 + sizeof...(Ts)>;

?

或者换句话说,const引用和推导指南中的值之间有什么区别吗?

Or, in other words is there any difference between const references and values in deduction guides?

请注意,问题不在于模板函数类型的推导,而在于新的C ++ 17功能,即用户定义的类模板参数推导的指南,因此您可以简单地声明A instance{1,2,3}而不是A<int, 3> instance{1,2,3}

Please note that the question is not about template function type deduction, but about the new C++17 feature, user-defined deduction guides for class template argument deduction, so you can simply declare A instance{1,2,3} instead of A<int, 3> instance{1,2,3}.

推荐答案

或者换句话说,const引用和推导指南中的值之间有什么区别吗?

Or, in other words is there any difference between const references and values in deduction guides?

在您的情况下,可能不是,但是一般来说是.

In your case maybe not but, generally speaking, yes.

T无法复制时.

在下面的示例中,第一种情况(常量引用)编译接收到std::unique_ptr<int>,第二种情况(值)给出错误

In the following example the first case (const reference) compile receiving a std::unique_ptr<int>, the second one (value) gives an error

#include <iostream>
#include <memory>

template <typename T, size_t N>
struct A
 { template <typename ... Ts> A (Ts const & ...) {} };

template <typename T, size_t N>
struct B
 { template <typename ... Ts> B (Ts const & ...) {} };

template <typename T, typename ... Ts>
A(T const &, Ts const & ...) -> A<T, 1U + sizeof...(Ts)>;

template <typename T, typename ... Ts>
B(T, Ts ...) -> B<T, 1 + sizeof...(Ts)>;


int main()
 {
   std::unique_ptr<int> up;

   auto a = A{up};    // compile
   // auto b = B{up}; // doesn't compile
 }

这篇关于推导中参考值与参考值之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆