简体   繁体   English

C ++ 17中带有参数包的类模板参数推导

[英]Class template argument deduction with a parameter pack in C++17

I am trying to implement class template argument deduction on a class. 我试图在一个类上实现类模板参数推导。 My class is templated over a type T ( will be a numeric) and the constructor over a std::size_t parameter pack. 我的类是在类型T (将是数字)上进行模板化的,而构造函数是在std::size_t参数包上进行模板化的。

#include <iostream>
#include <utility>
#include <experimental/array>

template < typename T, std::size_t S>
struct my_array
{               
    template < typename ...SizeTypes>
    my_array( SizeTypes&& ... s ):
    data( std::forward<std::array<std::size_t, S>>( std::experimental::make_array<std::size_t>( std::forward<SizeTypes>(s)... ) ) )
    { 
    }

    T value = T();
    std::array<std::size_t, S> data;
};

template <  typename T, class...Dimensions>
my_array( Dimensions&& ... )->my_array<T, sizeof...(Dimensions)>;

int main()
{   
    my_array<double> a(3, 4, 5);
    a.value = 2.32;
    std::cout << a.value << ", " << a.data[1] << std::endl;
    return 0;
}

I am getting the following error: 我收到以下错误:

prog.cc: In function 'int main()':
prog.cc:24:20: error: wrong number of template arguments (1, should be 2)
     my_array<double> a(3, 4, 5);

Demo 演示版

Any ideas on how to properly implement this? 关于如何正确实现这一点的任何想法?

T is non-deduced context here: T在这里是非推导上下文:

template <  typename T, class... Dimensions>
my_array( Dimensions&& ... )->my_array<T, sizeof...(Dimensions)>;

Since there's no way to deduce T , this deduction guide will never be selected. 由于无法推导T ,因此永远不会选择此推导指南。 None of the implicit guides are viable either. 任何隐式指南均不可行。

Instead, you should do as the standard library do: 相反,您应该像标准库那样做:

template <class T, class... U>
my_array(T, U...) -> my_array<T, 1 + sizeof...(U)>;

Also, as has been asked many many times before, this is not a thing: 而且,正如之前多次被问到的那样,这不是问题:

my_array<double> a(3, 4, 5);

You either deduce everything or deduce nothing . 您要么推论一切,要么一无所有 So this should either be: 因此,这应该是:

my_array<double, 3> a(3, 4, 5); // no deduction
my_array            b(3.0, 4, 5); // full deduction, b is also my_array<double, 3>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM