找到一个实现static_for
,而且它本身很简单:
using list = std::tuple<A, B, C, D, E, F, G, ...>;
const auto n = c - 'a';
static_for<std::tuple_size<list>()>([&](auto N){
if (n != N)
return;
using T = std::tuple_element_t<list, N>;
T obj(data, size);
obj.Something();
});
进一步考虑:
如果它们都具有相同的多态接口,您可以决定仅使用它来创建对象。
如果你的范围内有漏洞,if constexpr
and std::is_same
是你的朋友。
使用一些专用的类型列表类型可能比std::tuple
,但这在紧要关头有效。
一个未经修饰的、快速且肮脏的示例实现static_for()
:
template <std::size_t Is, class F>
void static_for_impl(F&& f, std::index_sequence<Is...>) {
f(std::integral_constant<std::size_t, Is>()), ...;
}
template <std::size_t N, class F>
void static_for(F&& f) {
static_for_impl(f, std::make_index_sequence<N>());
}