Lets say i have a class looking like this
template<int n>
class A{
array<size_t, n> sizes;
//...
public:
template <int k>
A<k> reshape(array<size_t, k> new_sizes){
return A<k>(new_sizes):
}
};
it works but the parameter new_sizes
is syntatically suboptimal, since i have to call it like that:
foo.reshape(array<size_t, 3>{1,2,3});
This does not work:
foo.reshape({1,2,3});
Is there a way to either define a initializer_list
with compile time size (so i could use it instead of the array) OR (even better) a way to define the size of a variadic parameter, so i could write something like
foo.reshape(1,2,3);
CodePudding user response:
OR (even better) a way to define the size of a variadic parameter, so i could write something like
foo.reshape(1,2,3);
You could take the sizeof...
a parameter pack:
template <size_t N>
class A {
std::array<size_t, N> sizes;
public:
A() = default;
template <class... Args>
A(Args&&... ss) : sizes{static_cast<size_t>(ss)...} {}
template <class... Args>
A<sizeof...(Args)> reshape(Args&&... new_sizes) {
// ^^^^^^^^^^^^^^^
return A<sizeof...(Args)>(static_cast<size_t>(new_sizes)...);
}
};
// deduction guide:
template <class... Args>
A(Args&&...) -> A<sizeof...(Args)>;
CodePudding user response:
{1, 2, 3}
has no type but can be deduced as initializer_list<T>
or T[N]
So to keep your syntax, it would be:
template <std::size_t K>
A<K> reshape(size_t (&new_sizes)[K])
{
return A<K>(new_sizes):
}
so i could write something like
foo.reshape(1,2,3);
For that variadic template:
template <typename... Ts>
A<sizeof...Ts> reshape(Ts... elems)
{
return reshape({elems...}); // using above method
}