tags:

views:

522

answers:

8

This is my code (simplification of a real-life problem):

class Foo {
public:
  void f(const string& s) {
    if (s == "lt") {
      return lt();
    } else if (s == "lte")
      return lte();
    } else if (s == "gt")
      return gt();
    } else if (s == "gte")
      return gte();
    }
  }
  void lt() { /* skipped */ }
  void lte() { /* skipped */ }
  void gt() { /* skipped */ }
  void gte() { /* skipped */ }
};

This is how I would do it in PHP/Python/JavaScript/many other languages (example in PHP):

class Foo {
  function f($s) {
    return $this->$s();
  }
  function lt() { /* skipped */ }
  function lte() { /* skipped */ }
  function gt() { /* skipped */ }
  function gte() { /* skipped */ }
}

How can I make my C++ code as elegant as this PHP example? Thanks in advance.

+34  A: 

There is no reflection in C++. However, something like a std::map<std::string, void (Foo::*)()>should do the trick.


EDIT: Here is some ugly code to do it maintainably. Note the following :

  • This can probably be improved in various way
  • Please add code to deal with non-existent tokens. I did no error checking.

#define BEGIN_TOKEN_MAP \
template <int n> \
struct add_to_ \
{ \
    static void act() {} \
}; \
std::map<std::string, void (Foo::*)()> map_;


#define DECLARE_TOKEN(str, n) \
template <> struct add_to_<n> \
{ \
    static void act() { map_[#str] = &Foo::##str; add_to<n+1>::act();} \
};\
void str()

#define END_TOKEN_MAP \
void init_map() { add_to_<0>::act(); } \
void process_token(std::string s) { (this->*map_[s])(); }


class Foo
{
    BEGIN_TOKEN_MAP
    DECLARE_TOKEN(lt, 0) { ... }
    DECLARE_TOKEN(gt, 1) { ... }
    ...
    END_TOKEN_MAP

    Foo() { init_map(); }
    void f(const std::string& s) { process_token(s); }
};
Alexandre C.
Macros and templates mixed... Wow! I'm half-tempted to take my upvote back ;-)
Steve314
macros and templates, to do something at runtime ! I'm not proud of this, but this is what you get when you want to use the wrong tool for the job...
Alexandre C.
I find it a bit over complex just to get a nice syntax,I think ezpz's or sbi's versions are clearer
fa.
the goal was to never repeat lt, gt, etc. I would never use such a thing in production code.
Alexandre C.
+4  A: 

C++ is not dynamic, so there is no exact equivalent. A little more elegant would be to use a map and possibly function objects.

Philipp
+9  A: 

You could use a dispatch table like:

typedef struct {
    char *name;
    void (*handler)();
} handler_t;

handler_t *handlers = {
    {"lt", &lt},
    {"lte", &lte},
    {"gt", &gt},
    {"gte", &gte},
    (NULL, NULL}
};

void f(const string &s) {
    for (int i=0; handlers[i].handler; ++i) {
        if (0 == strcmp(s.c_str(), handlers[i].name)) {
            handlers[i].handler();
            return;
        }
    }
}

See also this SO question: How do you implement a dispatch table in your language of choice?

the_void
what's the problem with std::map? We're talking c++
Nikko
There is no problem with the `c++` solution. Just a more general alternative (that happens to also work in `c`). I was editing my answer at the same time and I didn't see the post of Alexandre.
the_void
I'd use `std::pair<std::string,void(Foo::*)()>` instead of `handler_t` (the `typedef` is unnecessary in C++, BTW), and then use `handlers` to initialize [the map Alexandre brought up](http://stackoverflow.com/questions/3140683/3140711#3140711).
sbi
As I already pointed out, this also works in `C`, where you *should* use a `typedef`. However, I don't see why you'd use `std::pair` over `std::map`. If you want a pure `C++` solution, go with the `map`.
the_void
@the_void: See [my answer](http://stackoverflow.com/questions/3140683/3141225#3141225).
sbi
A: 

You have several possibilities. But the first thing I should say is that C++ is strongly typed. Therefore a method that handles an instance of Foo on the one hand and Foo on the other hand is of a different type from of method that handles Foo and Bar.

Now, let's suppose that you only wish to handle Foo objects. Then you have 2 solutions:

  • function pointers
  • function objects

The function object is more general, notably, it would allow you to specify multiple combinations of parameters in one object.

class OperatorBase
{
public:
  virtual ~OperatorBase() {}

  bool operator()(Foo const& lhs, Foo const& rhs) const;
  bool operator()(Foo const& lhs, Bar const& rhs) const;
  bool operator()(Bar const& lhs, Foo const& rhs) const;
  bool operator()(Bar const& lhs, Bar const& rhs) const;
private:
  // virtual methods to actually implement this
};

struct LessThanOperator: OperatorBase
{
  // impl
};

class OperatorFactory
{
public:
  static OperatorBase& Get(std::string const& name);

  template <class T>
  static void Register(std::string const& name);
private:
  typedef boost::ptr_map<std::string, OperatorBase> ops_t;
  static ops_t& Get() { static ops_t O; return O; }
};

And then you can proceed:

// Choose the operator
OperatorBase& op = OperatorFactory::Get("lt");

Foo foo;
Bar bar;

bool const result = op(foo, bar);

It's quite tedious work though.

Matthieu M.
I'm not sure why this would be down-voted. Maybe because the operators in `OperatorBase` are goofed up?
sbi
I don't know, people don't give reasons these days. But I'll patched it up nonetheless :p
Matthieu M.
+3  A: 

Following with the suggestion from Alexandre C., you can combine the std::map<... approach with an operator() to avoid having to call through to the void Foo::f.

For example:

class Foo {
   private:
      map<string,void (Foo::*)()> funs;
   public:
      // constructors etc.
      void operator () (const string& s) {
         if (funs.find (s) != funs.end ())
            (this->*funs[s])();
      }
      // remainder
};

And you can now use foo similar to

Foo f;
f("lt");  // calls Foo::lt ()
f("lte"); // calls Foo::lte ();
// etc...
ezpz
A: 

There are ways to do similar things in C++ with arrays and dynamic dispatch.

What you do is create an abstract class with some standard action(), like so:

class abstract_handler {
public:
   virtual void action () = 0;
}

Then you create subclasses with different implementations of action(). For example, for your "ffa" branch you might write:

class ffa_handler : public abstract_handler {
public:
   virtual action() {
      // Do your custom "ffa" stuff in here
   }

   // Add your custom "ffa" members for action() to work on here.
   // ...and of course a constructor to initialize them.
}

Then you create a map (in your case, indexed by std::string) of pointers to objects of each of your classes. At startup you populate this with the proper objects on the proper string indices. Then at runtime all you have to do is:

handler_map[index_string].action();

T.E.D.
+2  A: 
// Beware, brain-compiled code ahead!
namespace {
  typedef std::map<std::string, void (Foo::*)()> operations_map_t;
  typedef operations_map_t::value_type operations_entry_t;

  const operations_entry_t* operations = { {"lt" , &Foo::lt }
                                         , {"lte", &Foo::lte}
                                         , {"gt" , &Foo::gt }
                                         , {"gte", &Foo::gte} };
  const operations_map_t operations_map( operations 
                                       , operations + sizeof(operations)
                                                    / sizeof(operations[0]) );
}

void Foo::f(const string& s)
{
  operations_map_t::const_iterator it = operations_map.find(s);
  if(it == operations_map.end()) throw "Dooh!";
  it->second();
}
sbi
+2  A: 

I've upvoted Alexandre C, but I have reservations about building a data structure at run-time (populating the std::map) when the data is all known at compile-time.

I've upvoted the_void, but a linear search is only appropriate for relatively small data sets.

One option worth considering is a script (written in e.g. Python) to generate a hash-table or perfectly-balanced binary tree or whatever at build-time. You'll only do it if you have a recurring need to support large known-at-compile-time datasets, of course.

There's probably template-trickery ways to do this in C++ - they are Turing complete, and theres at least one compile-time parser state model generator, which is clearly more complex than a hash-table or binary tree. But personally, I wouldn't recommend it. A code-generating script will be simpler and more robust.

I have a script for generating ternary trees, but (1) it's a bit long for here, and (2) its not exactly a shining example of good coding.

Steve314
You cannot specialize a template on strings in C++, so this wouldn't be as neat as it could, for instance in D. But there must be some clever way to declare the functions and populate the table at the same place in the header, with some [ugly] macros.
Alexandre C.
I edited my answer to provide something along those lines.
Alexandre C.
@Alexandre C - If you're willing to trust maintainers, the simplest larger-dataset solution is probably a binary-searched array. The trouble is validating that it's correctly sorted at compile-time. Maybe a run-time initialisation check is OK, of course, but it's still an overhead. To me it's the automated build-time checks that are the real motivation for using a script, and I doubt that can be done with macros. Once that scripting decision is made, generating alternative data structures isn't such a big deal.
Steve314
Original question was "How can I make my C++ code as elegant as this PHP example?". So I assume no extra build-time tools, and go with standard c++ :)
Alexandre C.
@Alexandre C - Yours is easily the most elegant solution, no doubt about it. Still, sometimes pragmatic issues can override elegance, and it doesn't hurt to offer alternatives. I have no complaint about the difference between our respective vote-counts though - zero may be a little bit harsh, but this was never meant as a first-choice answer.
Steve314
Class methods are (or should be) only a few, so yes, the handler list that is searched is presumably small.
the_void