Writing generic functors
Hi all,
Maybe you already know this trick… Maybe not.
Maybe one day, you would have liked to write a functor with a total genericity…
Let’s say you have this functor.
1 2 3 4 5 6 7 | struct Printer { void operator() (const MyClass& obj) { std::cout << obj.toString() << endl; } }; |
Let’s imagine you have many other class that implements the toString() member function. Then, let’s try to add genericity to the previous code.
1 2 3 4 5 6 7 8 | template <class T> struct Printer { void operator() (const T& obj) { std::cout << obj.toString() << endl; } }; |
Nice try… But if we want to call our functor, we must specify T at our Printer’s declaration ! That’s not what we want. In fact, it would be great not to specify explicitly what T is when calling declarating and calling a Printer.
The problem in the previous code is that we have added genericity at a too high level… Indeed, templatizing operator() is really enough !
Let’s take a look.
1 2 3 4 5 6 7 8 | struct Printer { template <class T> void operator() (const T& obj) { std::cout << obj.toString() << endl; } }; |
Now, you’ll be able to call our functor on any object that has a toString() member function, moreover without specifying explicitly its type.



Leave a Comment