Noah Roberts wrote:
Frederick Gotham wrote:
I thought I might go about writing a class which would serve as a generic
function pointer. As this was just a pet project, I thought I'd make its
behaviour as well-defined as possible (to the extreme just for the craic!).
I'm designing the class in such a way that it should behave exactly like an
intrinsic function pointer type. I've also taken some liberties in writing
the code, e.g. the behaviour is undefined if you assign from an
uninitialised FuncPtr object.
Not to rain on your parade man but boost has this already. Check out
the function library. It will be in the next C++ standard and works
with things like bind, lambda, and all the algorithms in the std lib.
It's a pretty good wheel. Your time might be spent better on something
else.
Here's your original problem solved with boost::function:
#include <iostream>
#include <boost/any.hpp>
#include <boost/function.hpp>
void f1(int x) { std::cout << "void f1(int).\n"; }
void f2(double x) { std::cout << "void f2(double).\n"; }
int f3(double x) { std::cout << "int f3(double).\n"; return
static_cast<int>(x); }
void Func(boost::function<void (int)const & f)
{
f(42);
}
struct functor
{
void operator() (int x) { std::cout << "void functor::()(int).\n"; }
};
int main()
{
boost::function<void (int)f;
f = &f1;
Func(f);
f = &f2;
Func(f);
f = &f3;
Func(f);
Func(&f3);
functor fun;
Func(fun);
int y; std::cin >y;
return 0;
}
f can be assigned any invocable object that can be called with an int
as parameter and returns an object convertable to void. Func can be
used the same.