Search code examples
c++c++17variadic-functions

How to wrap C++ types into a list for variadic arguments


Related to an earlier question from me.

Just starting to use fold expressions, but it does not yet behave as I intend to. The background is that I want to be able to define 'my_list' in a dedicated header file to simplify maintenance. A call with separate types works, but when calling with 'my_list' it does not work. See comment in the example.

Is there a way to get the 2nd calling type working ?

template < typename ... Types > struct tl
{
};
using my_list = tl <int, float, uint64_t>;


    template <typename ... Types>
void myFunc2() 
{
    (std::cout << "Size: " << sizeof (Types) << std::endl, ...);     
} 

main () 
{
    myFunc2<int,uint64_t,bool,uint16_t>();  // This call prints size of each type
    myFunc2<my_list>();                     // This call only prints 1
} 

Solution

  • You need to specialize on your typelist (or perhaps any typelist). Using function object variable templates, this would be:

    template <typename ... Types>
    static constexpr auto myFunc2 = [] {
        (std::cout << "Size: " << sizeof (Types) << std::endl, ...);     
    };
    
    template <template<class...> class TL, typename ... Types>
    static constexpr auto myFunc2<TL<Types...>> = [] {
        (std::cout << "Size: " << sizeof (Types) << std::endl, ...);     
    };
    

    Example.