Difference between references and values in deduction guides

会有一股神秘感。 提交于 2019-12-13 14:19:32

问题


Considering type A:

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

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

and

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

?

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


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}.


回答1:


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.

When T isn't copyable.

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
 }



回答2:


A difference is that when using values in deduction guides, the arguments will decay for template argument deduction. For example,

#include <cstddef>
using std::size_t;

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

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

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

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

int main()
{
    int test[42];
    A instanceA {test}; // deduced to be A<int[42], 1>, error 
    B instanceB {test}; // deduced to be B<int*, 1>, ok but the effect may be unexpected
}


来源:https://stackoverflow.com/questions/51235025/difference-between-references-and-values-in-deduction-guides

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!