Skip to content

Instantly share code, notes, and snippets.

@ultrasilicon
Last active August 22, 2018 22:12
Show Gist options
  • Save ultrasilicon/645e7eb985d225254a983e989e9214ab to your computer and use it in GitHub Desktop.
Save ultrasilicon/645e7eb985d225254a983e989e9214ab to your computer and use it in GitHub Desktop.
Function Pointer Wrapper & Functor Wrapper using C++ Template
#include <iostream>
#include <list>
#include <unistd.h>
#include <functional>
#include <algorithm>
#include <chrono>
#include <iostream>
using namespace std;
using namespace std::chrono;
using namespace std::placeholders;
class Foo {
public:
int __attribute__((optimize("O0"))) add(int i, int j) {
i = i * j * j * i;
return i;
}
};
template<class T, typename Ret, typename... Args>
struct Function {
using F = Ret(T::*)(Args...);
T* o;
F f;
Function(T* obj, F func)
: o(obj)
, f(func)
{}
Ret call(Args... args) {
return (o->*f)(args...);
}
};
template<class T, typename Ret, typename... Args>
static Function<T, Ret, Args...> function_wrap(T *t, Ret(T::*f)(Args...))
{
Function<T, Ret, Args...> fp(t, f);
return fp;
}
template<class T, typename Ret, typename... Args>
struct Functor
{
using F = Ret (T::*)(Args...);
T *o;
F f;
Functor(T *obj, F func)
: o(obj)
, f(func)
{}
Ret operator()(Args... args)
{
return (o->*f)(args...);
}
};
template<class T, typename Ret, typename... Args>
Functor<T, Ret, Args...> functor_wrap(T *obj , Ret (T::*func)(Args...))
{
return Functor<T, Ret, Args...>(obj , func);
}
int main() {
Foo *foo = new Foo();
auto fp = function_wrap(foo, &Foo::add);
std::function<int(int, int)> ofp = functor_wrap(foo, &Foo::add);
std::function<int(int, int)> bfp = bind(&Foo::add, foo, _1, _2);
auto start = high_resolution_clock::now();
for (long int i = 0; i < 100000000; i++)
{
// fp.call(2,4);
// ofp(2,4);
bfp(2,4);
}
cout << "Time taken by function: "
<< duration_cast<microseconds>(high_resolution_clock::now() - start).count()
<< " microseconds"
<< endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment