Home > Software design >  Is there a way for a class template to deduce the size of a parameter pack passed to the constructor
Is there a way for a class template to deduce the size of a parameter pack passed to the constructor

Time:09-14

If I have a class template like such:

template<typename T, size_t N>
struct foo
{
    template<std::same_as<T>... Ts>
    foo(Ts... ts);
}

Is there any way whatsoever to deduce the template parameter N from the size of the parameter pack passed to the foo constructor? So that foo can be instantiated like so:

auto f = foo(10,10,10); // foo<int, 3>

Or is it simply impossible? Is there no getting around having to type foo<int, 3>(10,10,10)?

CodePudding user response:

Yes, a deduction guide for this is straight-forward:

template<typename T, typename... Ts>
requires (std::same_as<T, Ts> && ...) // optional
foo(T, Ts...) -> foo<T, sizeof...(Ts) 1>;

or

template<typename T, std::same_as<T>... Ts>
foo(T, Ts...) -> foo<T, sizeof...(Ts) 1>;
  • Related