简体   繁体   中英

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.

#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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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