I am new in c++ metaprogramming and few days ago I decided to write a template with variadic parameter pack, that knows in which position in parameter pack stands first int
. More precisely I want to have a struct
with name GetIntPos
and with static constexpr int
value which indicates the position of int
in parameter pack starting with 1, and 0 if there is no int
parameter type in parameter pack. For example
cout<<GetIntPos<long, char, int, long>::value; // must print 3
cout<<GetIntPos<int, int, long>::value; // must print 1
and
cout<<GetIntPos<long, long, char>::value; // must print 0;
How can it be done?
My recursive way
#include <iostream>
#include <type_traits>
template <std::size_t, typename ...>
struct GIP_helper
: public std::integral_constant<std::size_t, 0u>
{ };
template <std::size_t N, typename T0, typename ... Ts>
struct GIP_helper<N, T0, Ts...>
: public GIP_helper<N+1u, Ts...>
{ };
template <std::size_t N, typename ... Ts>
struct GIP_helper<N, int, Ts...>
: public std::integral_constant<std::size_t, N>
{ };
template <typename... Ts>
struct GetIntPos : public GIP_helper<1u, Ts...>
{ };
int main()
{
std::cout << GetIntPos<long, char, int, long>::value << std::endl;
std::cout << GetIntPos<int, int, long>::value << std::endl;
std::cout << GetIntPos<long, long, char>::value << std::endl;
}
Works starting from C++11.