J
James Aguilar
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
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