Allowing a functor or a function to be stored in a class

From: James Aguilar (jfa1_at_cec.wustl.edu)
Date: 03/30/05


Date: Tue, 29 Mar 2005 16:28:02 -0600

In the C++ STL, there are various places where you can call a function that
takes a functor as a parameter. This functor may be either a function object or
a function pointer. For instance, if you have a vector<char> and call for_each
on it, both of the methods below would be valid:

#include <iostream>
#include <vector>
using namespace std;

struct MyFunctionObject
{
  void operator ()(char a) {cout << a;};
};
void myFunction(char a) {cout << a;}

int main()
{
  vector<char> v;
  //fill it . . .
  for_each(v.begin(), v.end(), (MyFunctionObject()));
  for_each(v.begin(), v.end(), &myFunction);
  return 0;
}

My question pertains to a similar issue: how do I cause the same to occur in a
class template? I would like my template to look like this:

template <typename CompT>
class WhyWontThisWork
{
  CompT m_comparator;
public:
  WhyWontThisWork(CompT cmpIn) : m_comparator(cmpIn) {}
  void doThis(char a, char b) { if (m_comparator(a, b)) cout << "WIN"; }
};

Can I actually do this in C++ without writing an inordinate amount of code? If
so, how?

- JFA1



Relevant Pages

  • Re: Allowing a functor or a function to be stored in a class
    ... > takes a functor as a parameter. ... I would like my template to look like this: ... > class WhyWontThisWork ...
    (comp.lang.cpp)
  • Dynamic types based on existing template code
    ... already this template library with everything I want in it, ... inversion functor for Signal, e.g. Inv, I could have a functor ... class Wrapper ... Any hint or pointer to hints/pieces of code/libraries addressing this ...
    (comp.lang.cpp)
  • Help Please: Making a function template accept a default argument
    ... default arguement for the last parameter, ... template <typename T, typename FUNCTOR> ... I have tested that overloading the template with another template like ...
    (comp.lang.cpp)
  • Re: functors
    ... > a class and overload operator so that an object of the functor can be ... either pass an instance of a class or a pointer to a function to a template ... void operator; ... The latter can result in more efficient code because the compiler knows ...
    (comp.lang.cpp)