Search code examples
c++overloadingvariadic-templates

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

  • 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).