How can I directly use std::get instead of a Lambda function in std::transform?

Viewed 117

I have a std::vector of std::typle:

std::vector<std::tuple<int,int>> vt;

And I can transform the content of the vector to an other vector, by the algorithm std::transform, like this:

std::vector<int> vi(vt.size());

std::transform( vt.begin(), vt.end(), vi.begin(), [](auto &v) -> int {
    return std::get<0>(v);
} );   

Of course I could use a function too:

int myget(const std::tuple<int,int>& t)
{
    return std::get<0>(t);
}

std::vector<int> vi(vt.size());
std::transform( vt.begin(), vt.end(), vi.begin(), myget );


But would it be possible to use std::get directly, as a actual parameter in std::transform?

I mean somthing like this:

std::transform( vt.begin(), vt.end(), vi.begin(), std::get<0, ??? > );
1 Answers

Yes, it is possible, but I wouldn't recommend it at all. Because std::get has multiple overloads, you need to static_cast to the right one.

static_cast<int&(*)(std::tuple<int, int>&)>(&std::get<0, int, int>)

Really, that's not nice to look at, with repetition of template arguments two times. And if you want the cast to be generic, it will be pretty long.

Instead, to shorten your lambda, you can drop the -> int, as the return type will get automatically deduced:

std::transform( vt.begin(), vt.end(), vi.begin(), [](auto &v) {
    return std::get<0>(v);
} );

Someday, we might be able to write this:

std::transform(vt.begin(), vt.end(), vi.begin(), [](auto &v) => std::get<0>(v));
Related