Home > Blockchain >  Is it possible to pass one of the standard function templates as an argument without using a lambda?
Is it possible to pass one of the standard function templates as an argument without using a lambda?

Time:07-02

For example, std::get<N>.

Can I do the following without using a lambda somehow?

#include <iostream>
#include <tuple>
#include <algorithm>
#include <vector>
#include <iostream>

using str_and_int = std::tuple<std::string, int>;

std::vector<std::string> just_strings(const std::vector<str_and_int>& tuples) {
    std::vector<std::string> strings(tuples.size());
    std::transform(tuples.begin(), tuples.end(), strings.begin(),
        [](const auto& tup) {
            return std::get<0>(tup);
        }
    );
    return strings;
}

int main()
{
    std::vector<str_and_int> foo = { {"foo",1}, {"bar",2} ,{"quux",3}, {"mumble",4} };
    for (const auto& str : just_strings(foo)) {
        std::cout << str << "\n";
    }
    return 0;
}

Changing it to

std::transform(tuples.begin(), tuples.end(), strings.begin(), std::get<0, str_and_int>)

does not work. I am guessing because std::get is overloaded?

CodePudding user response:

You don't have to use a lambda. You could provide an instance of your own type if you'd like:

struct transformer {
    auto operator()(const auto& tup) const { // auto C  20
        return std::get<0>(tup);
    }
};

std::vector<std::string> just_strings(const std::vector<str_and_int>& tuples) {
    std::vector<std::string> strings(tuples.size());
    std::transform(tuples.begin(), tuples.end(), strings.begin(), transformer{});
    return strings;
}
  •  Tags:  
  • c
  • Related