Ecco un modo per farlo. Dato il tuo modello di classe some_other_type
:
template<int I, int J>
struct some_other_type { };
E dato alcuni macchinari nascosta nel detail
namespace:
namespace detail
{
template<int... Is>
struct pairs { };
template<int I, int J>
struct pairs<I, J>
{
using type = std::tuple<some_other_type<I, J>>;
};
template<int I, int J, int... Is>
struct pairs<I, J, Is...>
{
using type = decltype(std::tuple_cat(
std::tuple<some_other_type<I, J>>(),
typename pairs<J, Is...>::type()));
};
}
si potrebbe fornire una semplice funzione che crea un'istanza del modello di classe helper:
template<int... Is>
typename detail::pairs<Is...>::type pairs()
{
return typename detail::pairs<Is...>::type();
}
Ed ecco come lo useresti (e un caso di test):
#include <type_traits>
int main()
{
auto p = pairs<1, 2, 3, 4>();
// Won't fire!
static_assert(
std::is_same<
decltype(p),
std::tuple<
some_other_type<1,2>,
some_other_type<2,3>,
some_other_type<3,4>>
>::value,
"Error!");
}
Infine, ecco uno live example.
MIGLIORAMENTO: (perché la scrittura <1, 2, 3, 4>
in cui si poteva scrivere <1, 5>
)?
È anche possibile estendere la soluzione di cui sopra in modo che non sia necessario scrivere manualmente ogni numero tra il minimo e il massimo come argomento modello di pairs()
. Dato il meccanismo aggiuntivo di seguito, di nuovo nascosto in uno spazio dei nomi detail
:
namespace detail
{
template <int... Is>
struct index_list { };
template <int MIN, int N, int... Is>
struct range_builder;
template <int MIN, int... Is>
struct range_builder<MIN, MIN, Is...>
{
typedef index_list<Is...> type;
};
template <int MIN, int N, int... Is>
struct range_builder : public range_builder<MIN, N - 1, N - 1, Is...>
{ };
// Meta-function that returns a [MIN, MAX) index range
template<int MIN, int MAX>
using index_range = typename range_builder<MIN, MAX>::type;
template<int... Is>
auto pairs_range(index_list<Is...>) -> decltype(::pairs<Is...>())
{
return ::pairs<Is...>();
}
}
E 'possibile definire una funzione di supporto pairs_range()
che accetta 2 argomenti di template che definiscono la gamma [begin, end)
- dove end
non è incluso, nello stile del standard Library:
template<int I, int J>
auto pairs_range() -> decltype(pairs_range(detail::index_range<I, J>()))
{
return pairs_range(detail::index_range<I, J>());
}
E questo è come si potrebbe usarlo (compreso un caso di test):
int main()
{
// Won't fire!
static_assert(
std::is_same<
decltype(pairs_range<1, 5>()),
decltype(pairs<1, 2, 3, 4>())
>::value,
"Error!");
}
E ancora una volta, ecco uno live example.
+1 Questo è probabilmente realizzabile utilizzando una classe ... –