I want to find the position of the first occurrence of a value in std::integer_sequence.
- Is there an algorithm in the standard library for this task?
- If not, what would be a good way?
-
Below is my attempt. It works, but I do not find it very elegant; also, it cannot produce a pure error ("value not found") when this value is absent (code is commented out due to compilation). (Also, the need to specify an integer type in Find_in_integer_sequenceseems redundant, but I believe there is no way around it.)
The code is only for your entertainment, it should not be the starting point for the proposed solution.
# include <iostream>
# include <utility>
# include <type_traits>
namespace detail
{
template < int Idx, typename T, T Match, T ...Values >
struct Find;
template < int Idx, bool B, typename T, T Match, T ...Values >
struct Find_impl;
template < int Idx, typename T, T Match, T ...Values >
struct Find_impl<Idx, true, T, Match, Values...>
{
static const int value = Idx;
};
template < int Idx, typename T, T Match, T Value, T ...Other_values >
struct Find_impl<Idx, false, T, Match, Value, Other_values...>
: public Find<(Idx + 1), T, Match, Other_values...>
{
};
template < int Idx, typename T, T Match, T Value, T ...Other_values >
struct Find<Idx, T, Match, Value, Other_values...>
: public Find_impl<Idx, (Match == Value), T, Match, Value, Other_values...>
{
};
}
template < typename T, T Match, T ...Values >
struct Find
: public detail::Find<0, T, Match, Values...>
{
};
template < typename T, T Match, typename TIS >
struct Find_in_integer_sequence;
template < typename T, T Match, T ...Values>
struct Find_in_integer_sequence<T, Match, std::integer_sequence<T, Values...>>
: public Find<T, Match, Values...>
{
};
int main()
{
using i1 = std::integer_sequence<int, 2, 3, 3, 2, 3, 2, 0>;
auto k = Find_in_integer_sequence<int, 0, i1>::value;
std::cout << k << std::endl; # prints "6"
return 0;
}