Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract multiple types from tuple

Tags:

c++

c++11

tuples

That should be obvious, is there some short syntax to get a subtuple?

Something like that:

std::tuple<std::string, double, int> myTuple;
std::tuple<std::string, int> subTuple = std::get<std::string, int>(myTuple);
like image 818
Velkan Avatar asked Dec 29 '25 08:12

Velkan


1 Answers

You need to make your own template function, this below implementation requires C++14 (because it requires std::get<T>, you can implement it in C++11 yourself):

template<typename... R, typename ...Args>
std::tuple<R...> sub_tuple(const std::tuple<Args...>& original) {
    return std::make_tuple(std::get<R>(original)...);
}

int main()
{
    std::tuple<std::string, double, int> myTuple = std::make_tuple("Hello", 1201.0, 51);
    std::tuple<std::string, int> subTuple = sub_tuple<std::string, int>(myTuple);
    std::cout << std::get<0>(subTuple) << "            " << std::get<1>(subTuple);
}

Note: this will create a copy for each element in the original tuple

like image 60
Danh Avatar answered Dec 30 '25 22:12

Danh



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!