Oto sposób robienia tego. Biorąc pod uwagę, klasa szablon some_other_type
:
template<int I, int J>
struct some_other_type { };
A biorąc pod uwagę niektóre maszyny ukryty w detail
nazw:
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()));
};
}
Można zapewnić prostą funkcję, która tworzy wystąpienie szablonu klasy pomocnika:
template<int... Is>
typename detail::pairs<Is...>::type pairs()
{
return typename detail::pairs<Is...>::type();
}
A oto jak z niego korzystać (i przypadek testowy):
#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!");
}
Wreszcie, tutaj jest live example.
POPRAWA: (dlaczego pisanie <1, 2, 3, 4>
kiedy można napisać <1, 5>
)?
Możliwe jest również rozszerzenie powyższego rozwiązania, aby nie było wymagane ręczne zapisywanie każdej liczby między minimum a maksimum jako argumentu szablonu o wartości pairs()
. Ze względu na dodatkowy sprzęt poniżej znowu ukryty w detail
nazw:
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...>();
}
}
Możliwe jest zdefiniowanie funkcji pomocnika pairs_range()
która przyjmuje 2 argumenty szablonów określających zakres [begin, end)
- gdzie end
nie wliczono w stylu Biblioteka standardowa:
template<int I, int J>
auto pairs_range() -> decltype(pairs_range(detail::index_range<I, J>()))
{
return pairs_range(detail::index_range<I, J>());
}
a to w jaki sposób go używać (w tym przypadku testowego):
int main()
{
// Won't fire!
static_assert(
std::is_same<
decltype(pairs_range<1, 5>()),
decltype(pairs<1, 2, 3, 4>())
>::value,
"Error!");
}
I znowu tutaj jest live example.
+1 Prawdopodobnie jest osiągalne przy użyciu klasy ... –