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.
Asked: 2023-06-25 17:55:55 +0000
Seen: 8 times
Last updated: Jun 25 '23