Take the 2-minute tour ×

I have an object that contains, as part of its data, a linked list. Let's call this object LL, for reference sake.

I want to apply what I will call "operators" to instances of LL. So, an operator will, for instance, swap two elements of LL's linked list.

Ordinarily one might put such operators as methods of LL (so, you'd call LL.swap() or whatever) but I want to be able to define new types of operators.

The obvious thing to do, it seems to me, is to define an "Operator" class of objects that accept a pointer to an LL object when constructed. You could then call Operator.go() which would perform the swap.

However, this just doesn't seem right to me (for vague reasons I'm finding hard to articulate).

Other salient facts include:

  1. I will want to perform many of these operations in sequence (so perhaps the overhead should be as low as possible).
  2. There will usually only be a small number of LL objects instantiated.

Is defining an "Operator" class the way to go? Am I crazy for thinking it should be otherwise? The problem is: I'm having trouble imagining what "otherwise" might be. I haven't done any programming in a while and I'm slow in re-adjusting my brain to it.

share|improve this question
Naming a class like a C++ keyword (case apart) is IMO a very bad idea. That being apart, do you know what the STL is about, what functors are and what std::transform provides? –  Benoit Nov 9 '11 at 11:44
A free function is the common approach. It can even be templated for maximum generality. The downside is that you can only use the class's public interface. –  Kerrek SB Nov 9 '11 at 11:46
Instead of using a special method for the operator classes, just overload the operator() method? –  Joachim Pileborg Nov 9 '11 at 11:46
@Benoit: And do you know that the STL has no std namespace? And to which keyword are you referring? –  Lightning Racis in Obrit Nov 9 '11 at 11:47
@Tomalak Geret'kal: operator. Also I have read this answer several times. –  Benoit Nov 9 '11 at 11:54

1 Answer 1

up vote 1 down vote accepted

What you have thought of there is called the visitor-pattern, and it is a good and flexible way to add behavior to objects.

share|improve this answer
... where "good" and "flexible" are very relative :-) Alexandrescu says that the visitor pattern is terrible and ugly, but that it sometimes can be the right tool -- it depends very much on the nature of the code base. In general, it's appropriate when the class hierarchy is very stable and you just want to add new behaviour a lot. –  Kerrek SB Nov 9 '11 at 11:55
This may be exactly what I want (even taking @KerrekSB's comments into account). –  Bob Heffernan Nov 9 '11 at 12:16

Your Answer


