, , , . , , ++ 11 (aka ++ 0x) Boost, , , , , .
UncleBens, STL , ++ 11 Boost:
http://www.cplusplus.com/reference/std/functional/
, . , , .
( , ) stl, . , - / :
#include <iostream>
#include <functional>
using namespace std;
int addOne(int n)
{
return n + 1;
}
class timesTwo
{
public:
int operator()(int n) const { return n * 2; }
};
template <typename Functor>
void printResultImpl(Functor f, typename Functor::argument_type n)
{
typename Functor::result_type r = f(n);
cout << r << endl;
}
template <typename Arg, typename Result>
void printResult(Result (*f)(Arg), Arg n)
{
printResultImpl(ptr_fun(f), n);
}
template <typename Functor, typename Arg>
void printResult(Functor f, Arg n)
{
printResultImpl(bind1st(mem_fun(&Functor::operator()), &f), n);
}
int main()
{
printResult(addOne, 7);
printResult(timesTwo(), 7);
}
There are several restrictions for this method: 1. You cannot return your function for a result of a functor type (since the wrapper function does not know the type of result) 2. It relies on unary_function or binary_function in stl. As UncleBens demonstrated, you can expand to other types - just follow the ad template at:
http://www.cplusplus.com/reference/std/functional/
But he worked for what I needed; maybe this will work for someone else.
source
share