Skip to content

Instantly share code, notes, and snippets.

@thomaslee
Created January 15, 2013 07:50
Show Gist options
  • Save thomaslee/4537005 to your computer and use it in GitHub Desktop.
Save thomaslee/4537005 to your computer and use it in GitHub Desktop.
Unary function pointers in C++ for Dan W
#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