I want to implement a class FuncWrapper which behaves like below, but I find it is not so easy as expected.
int OrdinaryFunction(int n)
{
return n;
}
struct Functor
{
int operator ()(int n)
{
return n;
}
};
int main()
{
FuncWrapper<int(int)> f1(OrdinaryFunction);
cout << f1(1); // output 1;
Functor functor;
FuncWrapper<int(int)> f2(functor);
cout << f2(2); // output 2;
return 0;
}
My question is: How to implement the class FuncWrapper in PURE C++ (i.e, no STL) for making the code compiled?
I have partially implamented FuncWrapper showed below:
template<class T>
class FuncWrapper;
template<class ReturnType, class Parameter1>
class FuncWrapper<ReturnType(Parameter1)>
{
public:
typedef ReturnType (*FunctionPtr)(Parameter1);
template<class Functor>
FuncWrapper(Functor fn)
{
// ???
}
FuncWrapper(FunctionPtr fn)
: fn(fn)
{}
ReturnType operator ()(Parameter1 p1)
{
return this->fn(p1);
}
private:
FunctionPtr fn;
};