c++ - 重复使用相同模板函数的紧凑 switch 语句

标签 c++ c++11 templates

我有以下带有相当大的 switch 语句的 C++ 代码(我使用的是 C++11 编译器):

void function(std::size_t i, other_args)
{
   switch(i)
   {
      case 0:
         templatedfunction<0>(other_args);
         break;
      case 1:
         templatedfunction<1>(other_args);
         break;
      case 2:
         templatedfunction<2>(other_args);
         break;
      ...............
      //lots of other cases here
      ...............
      case 100:
         templatedfunction<100>(other_args);
         break;

   }  

}

哪里templatedfunction定义为

template<std::size_t T>
void templatedfunction(other_args){
   //some code here
}

这是用于描述一个简单概念的大量代码行(即调用 templatedfunction 并使用与传入其模板参数的变量 i 相同的值)。在 C++ 中有没有一种方法可以更紧凑地编写这段代码?应该有一种方法可以更紧凑地实现这个长 switch 语句....使用 templatedfunction<i>(other_args)i 后将无法编译是一个变量而不是编译时常量。谢谢。

最佳答案

非递归方法是创建函数指针数组,然后根据索引选择一个。

template<std::size_t... Is>
void function_impl(std::index_sequence<Is...>, std::size_t i)
{
    using func_t = void(*)();
    static constexpr std::array<func_t, sizeof...(Is)> fnc_arr = {
        (&templatedfunction<Is>)...
    };

    fnc_arr[i]();
}

void function(std::size_t i)
{
    function_impl(std::make_index_sequence<100>(), i);
}

看到它工作 here . 注意 std::index_sequence是 C++14,但可以在 C++11 中轻松实现。

编辑:

这里是 index_sequence 的简单实现.请注意,这是非常糟糕的实现,因为它是递归的并且深度为 O(N),因此它不会让您执行 make_index_sequence<5000>。你可以谷歌更好的实现。它也只是 index不是integer顺序。

template<std::size_t... Is>
struct index_sequence
{
    using type = std::size_t;

    static constexpr std::size_t size() noexcept
    {
        return sizeof...(Is);
    }
};

namespace detail
{
    template<std::size_t N, typename Seq>
    struct append;

    template<std::size_t N, std::size_t... Is>
    struct append<N, index_sequence<Is...>>
    {
        using type = index_sequence<Is..., N>;
    };


    template<std::size_t N>
    struct make_integer_seq
    {
        using type = typename append<N, typename make_integer_seq<N - 1>::type>::type;
    };

    template<>
    struct make_integer_seq<0>
    {
        using type = index_sequence<0>;
    };
}

template<std::size_t N>
using make_integer_sequence = typename detail::make_integer_seq<N - 1>::type;

关于c++ - 重复使用相同模板函数的紧凑 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53019091/

相关文章:

C++ STL 设置自定义比较器

c++ - 如何保存静态可选值

c++ - 模板规范问题

c++ - 需要引用标准关于 main 函数作为模板函数的合法性

c++ - 将成员函数分配给函数指针

c++ - 初始化矩阵和访问其数据的不同方法

c++ - unique_ptr 和指定解构函数

c++ - 将 std::function 绑定(bind)到不同对象实例的相同函数

c++ - 无法与 typedef 成为 friend : any particular reason?

django - 如何在收到信号时使 django 模板缓存 key 过期?