Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading