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?
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)
: TupleExtractor(tuple, std::make_index_sequence<std::tuple_size_v<Tuple>>{})
{}
ReturnType operator[](std::size_t index) const
{
return extractors[index](tuple);
}
private:
template <std::size_t I>
static ReturnType get(const Tuple& tuple)
{
return std::get<I>(tuple);
}
template <std::size_t ...I>
TupleExtractor(const Tuple& tuple, std::index_sequence<I...>)
: tuple(tuple),
extractors{&TupleExtractor::get<I>...}
{}
const Tuple& tuple;
using Extractor = ReturnType(*)(const Tuple&);
std::vector<Extractor> extractors;
};
and test - that it works:
int main() {
std::tuple<int, int, int> a{1,2,3};
TupleExtractor e{a};
return std::any_cast<int>(e[2]);
}