我有以下带有相当大的 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/