简体   繁体   中英

How can i pass std::get as an argument to a templated function?

What I want to do is this:

template <typename KeyType, typename Getter>
void one_function(KeyType& input,
                  Getter getter)
{
    std::cout << "inside one function " << getter(input) << std::endl;
}


int main(int argc, const char * argv[]) {
    auto aMap = std::unordered_map<std::string, std::pair<std::string, std::string> > { {"key1",{"value1_1","value1_2"} }, {"key2",{"value2_1","value2_2"}}};

    auto value_1_2 = one_function(aMap["key1"], std::get<1>);
}

I want to pass std::get<1> to a function to extract the second element of a tuple/pair. I know how to do this with lambdas, but I am curious how I can use std::get . Note: By using my own get function i can pass it to one_function but i don't know how to pass the standard library version

get has many overload, so you have to specify the correct one as:

one_function(aMap["key1"],
    static_cast<std::string&(*)(std::pair<std::string, std::string>&)>(&std::get<1>));

using lambda in C++14 is more readable:

one_function(aMap["key1"], [](auto& p){ return std::get<1>(p); });

Live example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM