Search code examples
c++templatesvariadic-templatesparameter-pack

Is there a way for a class template to deduce the size of a parameter pack passed to the constructor?


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


Solution

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