c++ - 使用折叠表达式打印每个元素之间的空格
问题描述
我正在使用折叠表达式来打印可变参数包中的元素,但是如何在每个元素之间获得一个空格?
当前输出为“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();
}
解决方案
你可以
#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)...)
推荐阅读
- omnet++ - OMNeT++ 文档在哪里?
- php - 如何在 PHP 中迭代 JSON 数组并显示元素?
- java - 内部类作为外部类的一部分
- scala - 如何重命名保存在 Azure 数据湖中的文件
- javascript - 在特定索引处合并两个数组
- azure-data-factory - 将 Azure 数据工厂连接到 SAP BW
- go - 为什么不能在赋值中使用 (type func(string)) 作为类型 func(interface{})
- jenkins - Jenkins hudson.TcpSlaveAgentListener$ConnectionHandler 运行连接失败
- apache-flink - Flink 中 KeyedBroadcastProcessFunction 的键控状态如何管理?
- javascript - 如何正确让我的按钮执行我的 javascript?