Suppose I have a tuple
std::tuple<A, B, C> myFavoriteTuple;
I can do this:
A a;
B b;
C c;
std::tie(a, b, c) = myFavoriteTuple
But if some of these tuples are really expensive to copy, what I'd really like is to take a reference or a pointer to the right spots in my tuple. I can do this:
A* a = &std::get<0>(myFavoriteTuple);
B* b = &std::get<1>(myFavoriteTuple);
C* c = &std::get<2>(myFavoriteTuple);
But that seems so lame compared to how awesome the tie
syntax is. Is there any other way to get pointers/references to the tuple components?
Given the usual indices infrastructure:
template<int... Is>
struct seq { };
template<int N, int... Is>
struct gen_seq : gen_seq<N - 1, N - 1, Is...> { };
template<int... Is>
struct gen_seq<0, Is...> : seq<Is...> { };
You could create a function that returns a tuple of pointers, each element being a pointer to the corresponding element of the input tuple:
template<typename... Args, int... Is>
auto make_pointer_tuple(std::tuple<Args...>& t, seq<Is...>)
-> std::tuple<typename std::add_pointer<Args>::type...>
{
return std::make_tuple(&std::get<Is>(t)...);
}
template<typename... Args>
auto make_pointer_tuple(std::tuple<Args...>& t)
-> std::tuple<typename std::add_pointer<Args>::type...>
{
return make_pointer_tuple(t, gen_seq<sizeof...(Args)>());
}
And this is how you could use it:
std::tuple<int, bool, std::string> myFavoriteTuple{0, false, ""};
int* pInt = nullptr;
bool* pBool = nullptr;
std::string* pString = nullptr;
tie(pInt, pBool, pString) = make_pointer_tuple(myFavoriteTuple);
Here is a live example.
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