gpt4 book ai didi

c++ - 拆分给定类型的参数包

转载 作者:太空宇宙 更新时间:2023-11-04 13:09:27 27 4
gpt4 key购买 nike

如何根据给定的分隔符类型拆分参数包?例如:

struct separator {
// ...
};

struct foo1 {
foo1(int a, int b) {...}
};

struct foo2 {
foo2(double a, double b, double c) {...}
};

template <typename... ArgsT>
void func(ArgsT&&... args) {
// args have two separators
auto f1 = foo1(/*How can I get the argument list to construct foo1?*/);
auto f2 = foo2(/*same as above*/);
auto f3 = ....
}

separator s1, s2;
func(s1, 1, 2, s2, 4.5, 6.7, 7.8);

在上面的例子中,给定的 args 保证至少有一个 separator 类型的参数。每个分隔符后跟一个参数列表以构造一个结构(例如,foo1foo2 等等)。将不胜感激基于 C++14 或 C++1z 的解决方案。

最佳答案

好的,我想我明白了,看看:

#include <functional>
#include <iostream>
template<typename T>
T recrusiveSearchHelper(int which,int current, T last)
{
return last;
};
template<typename T, typename... Args>
T recrusiveSearchHelper(int which,int current,T first,Args... args)
{
if (which == current)
{
return first;
}
recrusiveSearchHelper(which,current + 1,args...);
}
template <typename T,typename... Args>
T recrusiveSearch(int which, T first, Args... args)
{
return recrusiveSearchHelper(which,0,first,args...);
}


struct Seperator
{

};
void foo2(double a,double b,double d)
{
std::cout << "Foo two: " << a << " : " << b << " : " << d << std::endl;
};
void foo1(int a,int b)
{
std::cout << "Foo One: " << a << " : "<< b << std::endl;
};
void zipper(int& index,std::function<void(int)>fn, Seperator s)
{
index++;
fn(index);
}
template <typename T>
void zipper(int& index, std::function<void(int)>fn, T data)
{
index++;
};
template <typename T,typename... Args>
void zipper(int& index, std::function<void(int)> fn,T first, Args... args)
{
index++;
zipper(index,fn,args...);
};
template <typename... Args>
void zipper(int& index, std::function<void(int)> fn,Seperator first, Args... args)
{
index++;
fn(index);

zipper(index,fn,args...);
};
template <typename T,typename... Args>
void useWithSeperator(T first,Args... args)
{
int index = 0;
int current = 0;
std::function <void(int)> fn = [&current,first,args...](int where)
{
if (where - current == 3)
{

foo1(recrusiveSearch(where-3,first,args...),recrusiveSearch(where-2,first,args...));

}else if (where - current == 4)
{
foo2(recrusiveSearch(where-4,first,args...),recrusiveSearch(where-3,first,args...),recrusiveSearch(where-2,first,args...));
}
current = where;
};
zipper(index,fn,first);
zipper(index,fn,args...);
};
int main(int argc, char **argv)
{
useWithSeperator(1,2,3,Seperator(),4,5,Seperator(),1,1,2,3,4,Seperator(),1,2,5,Seperator());
}

它有点困惑,但是它所做的是通过一个辅助变量模板运行,该模板在每次迭代中缩小我们的搜索范围,直到元素首先成为其递归循环中我们所需位置的元素。剩下的就很简单了,我们需要检索数据并跟踪我们的周期有多长。

我会尽快为这个答案添加更多细节。

关于c++ - 拆分给定类型的参数包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40602202/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com