Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template that knows its argument's position

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?

like image 275
Vahag Chakhoyan Avatar asked Mar 12 '26 15:03

Vahag Chakhoyan


1 Answers

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
like image 115
Stephen Newell Avatar answered Mar 14 '26 06:03

Stephen Newell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!