Search code examples
c++templatesvariadic-templatesvariadic-functionsvariadic

Call variadic function template with template parameters of variadic class template?


Given a variadic class template, how can I call a variadic function template with the template parameters of that class?

Example:

template <typename T0,typename... Ts>
    void test_variadic()
{
    std::cout<<typeid(T0).name()<<std::endl;
    if constexpr (sizeof...(Ts) > 0)
        test_variadic<Ts...>();
}

template<typename T> // T is variadic class template
    void f0()
{
    // test_variadic<T...>(); // Call 'test_variadic' with underlying template parameter types of T? (In this example case `test_variadic<float,int>`)
}

template<typename ...T>
    class VariadicClass
{};

int main(int argc,char *argv[])
{
    f0<VariadicClass<float,int>>();
    return EXIT_SUCCESS;
}

The implementation for f0 is what I'm missing, I want it to call test_variadic<float,int> by determining the template parameter list from T automatically and using it for the call to test_variadic. How do I do that?

I found a solution that works with tuples:

#include <tuple>

template <typename T0,typename... Ts>
    void test_variadic()
{
    std::cout<<typeid(T0).name()<<std::endl;
    if constexpr (sizeof...(Ts) > 0)
        test_variadic<Ts...>();
}

int main(int argc, char **argv)
{
    std::tuple<int, float> tp;
    std::apply([](auto &&... args) { test_variadic<decltype(args)...>(); }, tp);
    return 0;
}

But in my case I don't have any actual arguments or objects, just types, so the lambda solution wouldn't work.

Solutions with modern C++ are preferred.


Solution

  • You can declare a class template with partial specialization as:

    // primary template (might implement it with default behavior)
    template <typename T> struct test_variadic_impl;
    
    // partial specialization for variadic class template
    template <template <typename...> typename C, typename... Args>
    struct test_variadic_impl<C<Args...>> {
        static auto call() {
            return test_variadic<Args...>();
        }
    };
    

    Then use it like:

    template<typename T> // T is variadic class template
        void f0()
    {
        test_variadic_imple<T>::call();
    }
    

    LIVE