I have a higher-order function, where the returned function captures the parameter of the wrapper function. the local version works, but the global version doesn't, and I don't understand why:
#include <iostream>
#include <sstream>
#include <iomanip>
const auto& parseDateTimeWithFormat = [](const std::string& formatStr) {
return [&formatStr](const std::string& dateTimeStr) {
std::cout << formatStr << std::endl;
tm t = {};
std::istringstream ss(dateTimeStr);
ss >> std::get_time(&t, formatStr.c_str());
const int timestamp = (int)mktime(&t);
return timestamp;
};
};
const auto& parseDateTime1 = parseDateTimeWithFormat("%Y-%m-%dT%H:%M:%SZ");
int main(int argc, const char* argv[]) {
int ts1 = parseDateTime1("2018-10-08T10:09:08Z");
std::cout << ts1 << std::endl;
const auto& parseDateTime2 = parseDateTimeWithFormat("%Y-%m-%dT%H:%M:%SZ");
int ts2 = parseDateTime2("2018-10-08T10:09:08Z");
std::cout << ts2 << std::endl;
return 0;
}
output:
(empty string)
-1
%Y-%m-%dT%H:%M:%SZ
1538989748
also, when capturing formatStr by value instead of by reference, the global version works, too.
Aucun commentaire:
Enregistrer un commentaire