Created
January 15, 2013 07:50
-
-
Save thomaslee/4537005 to your computer and use it in GitHub Desktop.
Unary function pointers in C++ for Dan W
This file contains hidden or 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
#include <iostream> | |
#include <map> | |
#include <functional> | |
class some_arg_t { | |
public: | |
some_arg_t(const char *name) : name_(name) {}; | |
const char *name() const { return name_.c_str(); } | |
private: | |
std::string name_; | |
}; | |
typedef std::pointer_to_unary_function<const some_arg_t &, int> fn_t; | |
typedef std::map<std::string, fn_t > fn_map_t; | |
int | |
do_a (const some_arg_t &arg) | |
{ | |
std::cout << "a: " << arg.name() << std::endl; | |
return 0; | |
} | |
int | |
do_b (const some_arg_t &arg) | |
{ | |
std::cout << "b: " << arg.name() << std::endl; | |
return 0; | |
} | |
int | |
main (int argc, char **argv) | |
{ | |
fn_map_t f; | |
some_arg_t arg("hello"); | |
f["a"] = std::ptr_fun (do_a); | |
f["b"] = std::ptr_fun (do_b); | |
const fn_t &fn = f["a"]; | |
fn (arg); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment