如何将c++模板发送到参数包中的包装元素

  • 本文关键字:参数 包中 元素 包装 c++ c++
  • 更新时间 :
  • 英文 :


现在我有一个特殊的要求。

  1. 函数处理的参数数量不是恒定的,所以我必须在C++中使用参数包

  2. 参数是std::pair<std:string, template>,但不同的参数具有不同类型的模板,因此args与std::pair<std::string, int>, std::pair<std::string, bool>, ...类似。实际上,我需要评估每个参数的类型,并根据类型执行不同的分支。在C++中,只有模板可以将typename作为参数进行传递。

  3. 一个可迭代类将是输入参数之一,所以我希望使用这个参数的大小,而不是变量参数的数量。

所以函数类似于这样:

template<typename... T>
template<typename pair_t> std::pair<std::string, T>
std::vector<ret_class> my_fun(const iterable_class &in_obj, pair_t &...type)
{
std::vector<ret_class> ret;
int i=0;
for(auto arg:type) // ergodic all variable parameters, but I hope to use the iterable_class.size() as the index limit.
{
ret.push(handle_fun<arg.second>(iterable_class[i])); // arg.second would change the behavior of handle_fun
++i;
}
return ret;
}

但是它不能通过编译。

有人能帮我澄清一下这个问题吗?

这看起来像是zip操作。给定一个参数包T0...Ti,则需要创建一个参数组std::pair<std::string, T0> ... std::pair<std::string, Ti>

声明很简单:

template<typename... T>
std::vector<ret_class> my_fun
(const iterable_class &in_obj, std::pair<std::string, T>&...type)
{ /****/ }

std::pair<std::string, T>&是一个模式,包含模板包标识符T,因此它是扩展的。

for(auto arg:type)位更令人费解。你不能在一组异构的参数上循环。auto会推断出什么类型?

递归地写这个可能更容易

template<typename HEAD, typename... Tail>
std::vector<ret_class> my_fun
(const iterable_class &in_obj, std::pair<std::string, HEAD> head, Tail&...tail)
{
auto in_head = iterable_class.front();
iterable_class.pop_front()
auto ret = my_fun(iterable_class, tail...);
ret.push_front(handle_fun<HEAD>(in_head));
return ret;
}
}
return ret;

最新更新