1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| #include <iostream>
#include <boost/function.hpp>
template <typename R> struct ifunction0;
template <typename R, typename P1> struct ifunction1;
struct ifunction_base {
template<typename R> R operator()();
template<typename R, typename P1> R operator()(P1 const&);
virtual ~ifunction_base() { }
};
template <typename R> struct ifunction0: ifunction_base {
typedef R (*fnType)();
ifunction0(fnType ptr) : myPtr(ptr) {}
R operator()()
{
return myPtr();
}
private:
fnType myPtr;
};
template <typename R, typename P1> struct ifunction1: ifunction_base
{
typedef R (*fnType)(P1 const&);
ifunction1(fnType ptr) : myPtr(ptr) {}
R operator()(P1 const& p1)
{
return myPtr(p1);
}
private:
fnType myPtr;
};
template <typename R> R ifunction_base::operator()()
{
ifunction0<R>* self = dynamic_cast<ifunction0<R>*>(this);
assert(self != 0); return self->operator()();
}
template <typename R, typename P1> R ifunction_base::operator()(P1 const& p1)
{
ifunction1<R, P1>* self = dynamic_cast<ifunction1<R, P1>*>(this);
assert(self != 0); return self->operator()(p1);
}
int f() { return 42; }
int main()
{
ifunction_base* pf = new ifunction0<int>(f);
std::cout << pf->operator()<int>();
return 0;
} |