紧凑的switch语句,使用重复相同的模板化函数

ast*_*bia 1 c++ templates c++11

我有以下C++代码和一个相当大的switch语句(我使用的是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;

   }  

}
Run Code Online (Sandbox Code Playgroud)

在哪里templatedfunction定义为

template<std::size_t T>
void templatedfunction(other_args){
   //some code here
}
Run Code Online (Sandbox Code Playgroud)

这是用于描述简单概念的许多代码行(即,templatedfunction使用i与其模板化参数中传递的变量相同的值调用).在C++中有没有办法更紧凑地编写这段代码?应该有一种方法可以更紧凑地实现这个long switch语句....使用templatedfunction<i>(other_args)不会编译,因为它i是一个变量而不是编译时常量.谢谢.

Zer*_*ges 5

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

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);
}
Run Code Online (Sandbox Code Playgroud)

看到它在这里工作.请注意,这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;
Run Code Online (Sandbox Code Playgroud)