我正在使用fold表达式来打印可变包装中的元素,但是如何在每个元素之间获得一个空格?
当前输出为“ 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();
}
答案 0 :(得分:7)
你可以
#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)...)
答案 1 :(得分:6)
通常,您将递归用于此类任务。
您必须定义当列表中有2个或更多和1个元素并递归回落到那些定义时会发生什么:
template <int ...> struct List;
template <int First, int Second, int ... More> struct List {
static void print() {
std::cout << First << " ";
List<Second, More ...>::print();
}
};
template <int Last> struct List {
static void print() {
std::cout << Last;
}
};
答案 2 :(得分:1)
您可以重用print()
来实现此行为。毕竟,您正在执行fold
操作,根据定义,该操作是递归的。
template<T head,T ... rest_of_pack>
struct List<head , rest_of_pack...>
{
static void print_()
{
std::cout<<head<<" ";
List<rest_of_pack...>::print();
}
};
如果您想以这种方式处理许多元素,则可能会遇到模板深度问题(例如,gcc的限制为900
)。幸运的是,您可以使用-ftemplate-depth=
选项来调整此行为。
您可以使用-ftemplate-depth=100000
进行编译并使其起作用。请注意,编译时间将激增(最有可能),或者在最坏的情况下,内存不足。
答案 3 :(得分:0)
如果仅在数字之间需要空格(并且在后一个或第一个之后也不需要),则可以这样做:
template <std::size_t ... Is>
void print_seq(std::index_sequence<Is...>)
{
const char* sep = "";
(((std::cout << sep << Is), sep = " "), ...);
}