c++indexingtuplesoperator-overloadingstd

Overload tuple indexing operator - C++


How can I overload indexing [] operator for std::tuple<int,int,int>? So when I have std::tuple<int,int,int> tup and I type tup[0] I want it to return the reference to get<0>(tup). Is this possible?


Solution

  • As mentioned in other answers - it is not possible to add any member function to std type like std::tuple. And operator[] has to be non-static member function.

    But you can wrap this tuple - and add operator[] to this wrapper type. In such case - you would need to know the common return type for all elements of tuple. Well - there is std::any which can work for most of types.

    This should work, but this is only to meet your curiosity - it would be bad design to use something like that in real software:

    template <typename Tuple, typename ReturnType = std::any>
    class TupleExtractor
    {
    public:
        TupleExtractor(const Tuple& tuple) 
            : tuple(tuple)
        {}
        
        ReturnType operator[](std::size_t index) const
        {
            return extractors[index](tuple);
        }
    
    private:
        const Tuple& tuple;
    
       static constexpr auto extractors = []<template <typename T, T...> class L, std::size_t ...I>(L<std::size_t, I...>) {
            return std::array{+[](const Tuple& t) -> ReturnType { return std::get<I>(t); }...};
        }(std::make_index_sequence<std::tuple_size_v<Tuple>>());
    };
    

    and test - that it works:

    int main() {
        std::tuple<float, char, int> a{1.0, '2', 3};
        TupleExtractor e{a};
        
        return std::any_cast<int>(e[2]);
    }