Live data from Hacker News

Grim C++ Tales from the Crypt: The Visitor Pattern (2017)

cppcrypt.tumblr.com

61–64 of 64 posts

Re: Grim C++ Tales from the Crypt: The Visitor Pattern (2017)

#61
post #16

This... I can actually see the point in this. The Visitor pattern is one of those patterns I never really saw the point of, and which mostly struck me as an over-engineered hack about a shortcoming in a language. This example actually makes clear why you'd need to do it this was in C++ at least. Not sure which other languages would need this. It's certainly not pretty. Then again, dispatching twice is not so bad comp…

A state machine with context is one case I have used it for.

Re: Grim C++ Tales from the Crypt: The Visitor Pattern (2017)

#63

Earlier quoted context omitted.

Why have functions and control structures when we can just jmp?

That's a disingenuous comparison. Functions are used pervasively, but even the visitor pattern isn't used very often.

But in languages that support multiple dispatch at the language level, they're just another way of writing polymorphic functions. They're not just a niche feature. When you don't have to write all of the ceremony of the visitor pattern, it's easier to use visitors everywhere without thinking about them.

Re: Grim C++ Tales from the Crypt: The Visitor Pattern (2017)

#64

I don't understand why the class instance needs to accept the interaction. Why not just invoke the interaction directly? interactor_p->interact(thingy_p) Would this still be considered the visitor pattern or is the extra layer of indirection important?

I don't know about the limitations of C++, but something like what you describe would happen in Smalltalk. Take for example a Canvas object and a bunch of different shape objects (square, circle, etc):

  "Square class"
  drawOn: aCanvas
      aCanvas line: (some point) to: (some point).
      "etc"
  
  "Triangle class"
  drawOn: aCanvas
      aCanvas line: self leftVertex to: self rightVertex.
      "etc"

  "Canvas class"
  drawShapes: aCollection
      aCollection do: [ :shape |
          shape drawOn: self ]
Post reply on HN