首页 > 解决方案 > 使用折叠表达式打印每个元素之间的空格

问题描述

我正在使用折叠表达式来打印可变参数包中的元素,但是如何在每个元素之间获得一个空格?

当前输出为“1 234”,所需输出为“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();
}

标签: c++coutfold-expression

解决方案


你可以

#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();
}

折叠表达式((std::cout << " " << list), ...)将扩展为((std::cout << " " << list1), (std::cout << " " << list2), (std::cout << " " << list3)...)


推荐阅读