Allowing a functor or a function to be stored in a class
From: James Aguilar (jfa1_at_cec.wustl.edu)
Date: 03/30/05
- Next message: Pete Becker: "Re: Allowing a functor or a function to be stored in a class"
- Previous message: Victor Bazarov: "Re: please explain why this is Undefined Behavior"
- Next in thread: Pete Becker: "Re: Allowing a functor or a function to be stored in a class"
- Reply: Pete Becker: "Re: Allowing a functor or a function to be stored in a class"
- Reply: Victor Bazarov: "Re: Allowing a functor or a function to be stored in a class"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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
- Next message: Pete Becker: "Re: Allowing a functor or a function to be stored in a class"
- Previous message: Victor Bazarov: "Re: please explain why this is Undefined Behavior"
- Next in thread: Pete Becker: "Re: Allowing a functor or a function to be stored in a class"
- Reply: Pete Becker: "Re: Allowing a functor or a function to be stored in a class"
- Reply: Victor Bazarov: "Re: Allowing a functor or a function to be stored in a class"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|