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?
This seems to work in my tests:
namespace detail {
template <int INDEX>
constexpr int GetIntPosImpl() {
return 0;
}
template <int INDEX, typename T, typename ...Ts>
constexpr int GetIntPosImpl() {
if constexpr(std::is_same_v<T, int>) {
return INDEX;
}
else {
return GetIntPosImpl<INDEX + 1, Ts...>();
}
};
}
template <typename ...Ts>
struct GetIntPos {
static constexpr int value = detail::GetIntPosImpl<1, Ts...>();
};
int main() {
std::cout << GetIntPos<short, long, char>::value << '\n';
std::cout << GetIntPos<int, short, long, char>::value << '\n';
std::cout << GetIntPos<short, long, char, int>::value << '\n';
return 0;
}
My output:
0
1
4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With