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

How to overload variadic template function based on size of parameter pack in C++

I’m sorry if this question is basic. Let’s say I have a function template that took in a parameter pack of arguments. How would I overload it so that there might be a specialization for 2 arguments getting passed in, 3 arguments passed in, etc.

>Solution :

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

For small parameter packs, I’d use non-variadic overloads:

template <typename A, typename B> void foo(A a, B b);
template <typename A, typename B, typename C> void foo(A a, B b, C c);

If you prefer to have a pack, you can constrain the size with requires or std::enable_if_t:

template <typename ...P> requires(sizeof...(P) == 2) void foo(P ...p);
template <typename ...P> requires(sizeof...(P) == 3) void foo(P ...p);

Another option is to have a single variadic function, and select the behavior with if constexpr (sizeof...(P) == N).

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