Skip to content

Instantly share code, notes, and snippets.

@azmfaridee
Created August 5, 2013 13:22
Show Gist options
  • Save azmfaridee/6155878 to your computer and use it in GitHub Desktop.
Save azmfaridee/6155878 to your computer and use it in GitHub Desktop.
Using C++11's lambda to generate desired functions with a factory.
#include <iostream>
#include <vector>
std::function<float(float)> converter_factory(std::string region) {
if (region == "US") {
return [] (float celsius) -> float {
return (celsius / 5 * 9 + 32);
};
}
return [] (float fahrenheit) -> float {
return ((fahrenheit - 32) / 9 * 5);
};
};
int main(int argc, const char * argv[]) {
std::function<float(float)> us_converter = converter_factory("US");
std::function<float(float)> uk_converter = converter_factory("UK");
std::cout << us_converter(100) << std::endl;
std::cout << uk_converter(100) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment