Ask Your Question
1

Can a templatized lambda be utilized as a value (represented by std::function) in an unordered map?

asked 2023-06-25 17:55:55 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-06-25 18:14:02 +0000

scrum gravatar image

Yes, a templatized lambda can be utilized as a value in an unordered map if the type of the lambda can be determined at compile time. You can use std::function as the value type of the unordered map to store the lambda. Here is an example:

#include <iostream>
#include <unordered_map>
#include <functional>

int main()
{
    // Define an unordered map with std::function as the value type.
    std::unordered_map<std::string, std::function<void(int)>> functionMap;

    // Insert a lambda function that takes an int argument and prints it.
    functionMap.insert({"print", [](int x){ std::cout << x << std::endl; }});

    // Call the lambda function by invoking it from the unordered map.
    functionMap["print"](123);

    return 0;
}

In this example, we define an unordered map functionMap with std::string as the key type and std::function<void(int)> as the value type. We insert a lambda function that takes an int argument and prints it using std::cout. We then call the lambda function by invoking it from the unordered map using the key "print".

Note that if the type of the lambda cannot be determined at compile time, such as when it captures local variables or uses type deduction, it cannot be stored as a value in an unordered map.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-25 17:55:55 +0000

Seen: 8 times

Last updated: Jun 25 '23