Monday, July 31, 2006

Function generator in C++

Cross-posted from http://blogs.msdn.com/abhinaba/archive/2005/08/12/450868.aspx

Some of us were just chatting about my previous post about function generators and we wondered about whether it can be done in C++ without using function pointers.... Most of my C++ knowledge has been rusted beyond repair but I thought even though its not possible to do directly, one can overload the ( ) operator to simulate this. So it should be possible to code so that the following is valid

FuncGen(Adder)(p1, p2)


Here the part in red semantically behaves like a function generator returning different functions based on the flag you pass. So here's some code in C++ that does it. Again I want to stress that this is not a function generator in C++, it just simulates something like it so that a statement like FuncGen(Adder)(p1, p2) will actually work....


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


enum FuncType
{
Adder,
Subtractor,
Multiplicator,
};


class CFunc
{
public
:
FuncType m_funcType;
template <typename
T>
T
operator
()(T p1, T p2)
{
if
(m_funcType == Adder)
return
FuncAdder(p1, p2);
else if
(m_funcType == Subtractor)
return
FuncSub(p1, p2);
else if
(m_funcType == Multiplicator)
return
FuncMult(p1, p2);
}


private:
template <typename
T>
T FuncAdder(T p1, T p2)
{
return
p1 + p2;
}
template <typename
T>
T FuncSub(T p1, T p2)
{
return
p1 - p2;
}
template <typename T>
T FuncMult(T p1, T p2)
{
return
p1 * p2;
}
};


CFunc cfunc;
CFunc& FuncGen(FuncType ftype)
{
cfunc.m_funcType = ftype;
return
cfunc;
};


int main(int argc, char* argv[])
{
int
p1 = 5, p2 = 1;
cout << FuncGen(Adder)(p1, p2) << endl;
cout << FuncGen(Subtractor)(p1, p2) << endl;
cout << FuncGen(Multiplicator)(p1, p2) << endl;
return
0;
}


Instead of using a global variable like cfunc I could have also created a object on the heap in FuncGen and later deleted it but since I have been coding in C# so long that I felt too lazy to write a delete statement.

No comments: