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.
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
Asked: 2023-06-25 17:55:55 +0000
Seen: 8 times
Last updated: Jun 25 '23
In a constexpr context, what is the method for invoking ExecutionPolicy algorithms?
Can using std::string as a wrapper for hashing raw buffer be problematic?
What is the definition of the operator < for std::set that uses pointers?
What is the C equivalent of std::byte (that can handle IO operations correctly)?
What is the method for using std::sqrt as a parameter?
How can I format the output of cout to be aligned with the columns of a table?