Last active
April 24, 2016 15:56
-
-
Save ducalpha/57c97e0521578fc2b7dc13087fe25db4 to your computer and use it in GitHub Desktop.
Map function lambda functions C++. Demo factory method, polymorphism, lambda functions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright 2016 Duc Hoang Bui, KAIST. All rights reserved. | |
// Licensed under MIT | |
#include <iostream> | |
#include <string> | |
#include <map> | |
#include <memory> | |
#include <functional> | |
struct Animal { | |
virtual void Speak() { | |
std::cout << "Animal speak\n"; | |
} | |
}; | |
struct Cat : public Animal { | |
virtual void Speak() override { | |
std::cout << "Cat meo\n"; | |
} | |
}; | |
struct Dog : public Animal { | |
virtual void Speak() override { | |
std::cout << "Dog bark\n"; | |
} | |
}; | |
int main() | |
{ | |
std::map<std::string, std::function<std::unique_ptr<Animal>()>> test_map{ | |
{"animal", []() {return std::unique_ptr<Animal>(new Animal());} }, | |
{"cat", []() {return std::unique_ptr<Animal>(new Cat());} }, | |
{"dog", []() {return std::unique_ptr<Animal>(new Dog());} } | |
}; | |
test_map["animal"]()->Speak(); | |
test_map["cat"]()->Speak(); | |
test_map["dog"]()->Speak(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment