C ++将类型的参数包转换为索引的参数包 [英] C++ Convert a parameter pack of types to parameter pack of indices

查看:97
本文介绍了C ++将类型的参数包转换为索引的参数包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何方法将类型的参数包转换为整数的参数包从 0 sizeof ...(Types)?更具体地说,我试图这样做:

Is there any way to convert a parameter pack of types to a parameter pack of integers from 0 to sizeof...(Types)? More specifically, I'm trying to do something this this:

template <size_t... I>
  void bar();

template <typename... Types>
  void foo() {
    bar<WHAT_GOES_HERE<Types>...>();
  }

例如, foo< int,float,double> ;()应该调用 bar< 0,1,2>();

在我的使用情况下,参数包 Types 可能包含相同的类型多次,所以我不能搜索包计算给定类型的索引。

In my use case the parameter pack Types may contain the same type multiple times, so I cannot search the pack to compute the index for a given type.

推荐答案

在C ++ 14中,你可以使用 std :: index_sequence_for $ c>< utility> 标题以及标记分发。这被称为 indices trick

In C++14 you can use std::index_sequence_for from the <utility> header along with tagged dispatch. This is known as the indices trick:

template <std::size_t... I>
void bar(std::index_sequence<I...>);

template <typename... Types>
void foo() {
    bar(std::index_sequence_for<Types...>{});
}

如果你只能使用C ++ 11,上面的在线,如这一个

If you are limited to C++11, you can find many implementations of the above online, such as this one.

这篇关于C ++将类型的参数包转换为索引的参数包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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