使用折叠表达式在每个元素之间打印空格 [英] Print spaces between each element using a fold expression

查看:82
本文介绍了使用折叠表达式在每个元素之间打印空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

当前输出为 1 234,所需的输出是 1 2 3 4。

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


推荐答案

您可以

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

这篇关于使用折叠表达式在每个元素之间打印空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆