Is it possible to use a generic templatized lambda as value (std::function) in an unordered map?
I want to achieve to scan a file for keywords and then read the corresponding data from the file in a dedicated variable/place in a data structure.
I created a minimum reproducible example, where I use a std::tuple
as the data structure and a normal template function as the value (using std::function
) in an std::unordered_map
.
Please see the simple working code:
#include <iostream>
#include <sstream>
#include <unordered_map>
#include <string>
#include <functional>
#include <tuple>
using namespace std::string_literals;
// The tuple (instead of using a struct)
using Data = std::tuple<int, int, long, double>;
// Generic read for the above defined tuple
template <std::size_t Index>
std::istream& read(std::istream& is, Data& d) { is >> std::get<Index>(d); return is; }
// Test data
std::istringstream iss{ R"(int0 0
int1 1
some nonsense in the data
long 2
double 3.3)" };
// Test code
int main() {
// Our data structure
Data data{};
// Map the read function to a pattern or keyword
std::unordered_map<std::string, std::function<std::istream& (std::istream&, Data&)>> reader{{"int0"s,read<0>},{"int1"s,read<1>},{"long"s,read<2>},{"double"s,read<3>}};
// Read all data
for (std::string type{}; iss >> type; reader.contains(type) and reader[type](iss,data))
;
// Debug output
std::cout << std::get<0>(data) << '\n' << std::get<1>(data) << '\n' << std::get<2>(data) << '\n' << std::get<3>(data) << '\n';
}
You can run the above code in compiler explorer.
I would like to use a generic template lambda instead of the global "read" function, and put that, as value, via a std::function
into the std::unordered_map
.
I found a similar problem here. But there, the template parameter is used as argument in the lambda, which would influence the std::function
s signature.
So, I am really not sure.
Is my idea achievable at all? And if, how?