Search code examples
c++coutfold-expression

Print spaces between each element using a fold expression


I am using a fold expression to print elements in a variadic pack, but how do I get a space in between each element?

Currently the output is "1 234", the desired output is "1 2 3 4"

template<typename T, typename Comp = std::less<T> >
struct Facility
{
template<T ... list>
struct List
{
    static void print()
    {

    }
};
template<T head,T ... list>
struct List<head,list...>
{
    static void print()
    {
     std::cout<<"\""<<head<<" ";
     (std::cout<<...<<list);
    }
};
};

template<int ... intlist>
using IntList = typename Facility<int>::List<intlist...>;
int main()
{
 using List1 = IntList<1,2,3,4>;
 List1::print();
}

Solution

  • you can that

    #include <iostream>
    
    template<typename T>
    struct Facility
    {
    template<T head,T ... list>
    struct List
    {
        static void print()
        {
         std::cout<<"\"" << head;
         ((std::cout << " " << list), ...);
          std::cout<<"\"";
        }
    };
    };
    
    template<int ... intlist>
    using IntList = typename Facility<int>::List<intlist...>;
    int main()
    {
     using List1 = IntList<1,2,3,4>;
     List1::print();
    }
    

    the fold expression ((std::cout << " " << list), ...) will expands to ((std::cout << " " << list1), (std::cout << " " << list2), (std::cout << " " << list3)...)