Skip to content

Instantly share code, notes, and snippets.

@mattmcd
Created June 8, 2013 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattmcd/5734781 to your computer and use it in GitHub Desktop.
Save mattmcd/5734781 to your computer and use it in GitHub Desktop.
Trying out lambdas and std::function in C++11
all: test_Factory
test_Factory: test_Factory.cpp
$(CXX) -std=c++0x -o test_Factory test_Factory.cpp
#include <iostream>
#include <map>
#include <functional>
class Foo {
public:
Foo(int Bar_) : Bar(Bar_) { }
int Bar;
};
int main()
{
auto f = []() { return 1; };
std::cout << f() << std::endl;
auto g = [](int i){ return new Foo(i); };
std::map< std::string, std::function<Foo* (int)> > fooMap;
fooMap[ "foo"] = g;
auto x = g(2);
std::cout << x->Bar << std::endl;
delete x;
auto y = fooMap["foo"](3);
std::cout << y->Bar << std::endl;
delete y;
std::function<int ()> h = []() { return 4; };
std::cout << h() << std::endl;
std::map< std::string, std::function<int ()> > theMap;
theMap[ "foo"] = []() { return 5; };
theMap[ "bar"] = []() { return 6; };
std::cout << theMap["foo"]() << std::endl;
std::cout << theMap["bar"]() << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment