C ++ 11在运行时索引元组而不使用开关的方法 [英] C++11 way to index tuple at runtime without using switch

查看:17
本文介绍了C ++ 11在运行时索引元组而不使用开关的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段类似如下的 c++11 代码:

I have a piece of c++11 code similar like below:

switch(var) {
   case 1: dosomething(std::get<1>(tuple));
   case 2: dosomething(std::get<2>(tuple));
   ...
}

有什么办法可以去掉这个大开关吗?请注意,get<var> 不起作用,因为 var 不是常量,但我知道 var 的范围很小,即 (0-20).

Is there any way to remove this large switch ? Note that get<var> does not work because var is not constant, but I know var is in small range i.e. (0-20).

注意这里的重点是避免使用导致数组查找的数组...

Note that the point here is to avoid using an array that causes an array lookup...

关于性能的问题,有讨论函数数组在 if 和 switch 语句中的性能

well on the issue of performance, there is a discussion Performance of array of functions over if and switch statements

出于我自己的目的,我不争论哪个更好.

For my own purpose, I do not argue which one is better.

推荐答案

这是一个不使用索引序列的版本:

Here's a version that doesn't use an index sequence:

template <size_t I>
struct visit_impl
{
    template <typename T, typename F>
    static void visit(T& tup, size_t idx, F fun)
    {
        if (idx == I - 1) fun(std::get<I - 1>(tup));
        else visit_impl<I - 1>::visit(tup, idx, fun);
    }
};

template <>
struct visit_impl<0>
{
    template <typename T, typename F>
    static void visit(T& tup, size_t idx, F fun) { assert(false); }
};

template <typename F, typename... Ts>
void visit_at(std::tuple<Ts...> const& tup, size_t idx, F fun)
{
    visit_impl<sizeof...(Ts)>::visit(tup, idx, fun);
}

template <typename F, typename... Ts>
void visit_at(std::tuple<Ts...>& tup, size_t idx, F fun)
{
    visit_impl<sizeof...(Ts)>::visit(tup, idx, fun);
}

演示

这篇关于C ++ 11在运行时索引元组而不使用开关的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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