Skip to content

Instantly share code, notes, and snippets.

@brycelelbach
Created October 13, 2010 21:03
Show Gist options
  • Select an option

  • Save brycelelbach/624912 to your computer and use it in GitHub Desktop.

Select an option

Save brycelelbach/624912 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
#include <string>
#include "function_object_adaptor.hpp"
struct base { virtual ~base (void) { } };
struct element: base { };
struct pack: base { };
struct functor {
typedef std::string result_type;
mutable result_type stateful_result;
result_type& get (void) const { return stateful_result; }
result_type* ptr (void) const { return &stateful_result; }
// dispatch uses polymorphism for this example cause I'm lazy
void operator() (std::vector<base*>::iterator it) {
base* b = *it; element* e = 0; pack* p = 0;
if ((e = dynamic_cast<element*>(b))) dispatch(e);
else if ((p = dynamic_cast<pack*>(b))) dispatch(p);
else dispatch(b);
}
void dispatch (base* b) {
stateful_result = "base";
}
void dispatch (element* e) {
stateful_result = "element";
}
void dispatch (pack* p) {
stateful_result = "pack";
}
};
int main (void) {
// this example uses polymorphism and therefore is crappy, but gives you
// the general idea of how this would work.
std::vector<base*> dataset;
dataset.push_back(new element);
dataset.push_back(new pack);
dataset.push_back(new element);
typedef function_object_adaptor<std::vector<base*>::iterator, functor>
functor_iterator;
std::vector<base*>::iterator data = dataset.begin(),
end = dataset.end();
functor_iterator fit(data/*, functor()*/); // second arg is defaulted
do {
std::cout << *fit << std::endl;
} while (!((++fit).at(end)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment