Home > Blockchain >  How to overload variadic template function based on size of parameter pack in C
How to overload variadic template function based on size of parameter pack in C

Time:10-09

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.

CodePudding user response:

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

CodePudding user response:

You can just overload function templates since it is not possible to partially specialize a function template:

template<typename... T> 
void f(T...)
{
    std::cout << "variadic version called" << std::endl;
}
//overload for 2 args 
template<typename T, typename V>
void f(T, V)
{
    std::cout << "2 version called" << std::endl;
}
//overload for 3 args 
template<typename T, typename V, typename U>
void f(T, V, U)
{
    std::cout << "3 version called" << std::endl;
}
int main()
{
    f(3,3,4,5); //calls #1 
    f(2,4.4);   //calls #2 
    f(33,6,4);   //calls #3
}

Demo.

  • Related