I am looking for a way to decorate functions or lambdas in C++. The goal is to do something before and after the function call. As I've seen the closest thing to use is std::function but it needs to have the types of its arguments.
class FunctionDecorator
{
public:
FunctionDecorator( std::function func )
: m_func( func )
void operator()()
{
// do some stuff prior to function call
m_func();
// do stuff after function call
}
private:
std::function m_func;
};
It would be great if by template type could be used in std::function and it could deduce it somehow when i pass pointer to a function or a result from std::bind.
Is such thing possible in C++.
Hmm. I may or may not have gone overkill.
#include <type_traits>
#include <utility>
#include <iostream>
template <class T>
struct RetWrapper {
template <class Tfunc, class... Targs>
RetWrapper(Tfunc &&func, Targs &&... args)
: val(std::forward<Tfunc>(func)(std::forward<Targs>(args)...)) {}
T &&value() { return static_cast<T &&>(val); }
private:
T val;
};
template <>
struct RetWrapper<void> {
template <class Tfunc, class... Targs>
RetWrapper(Tfunc &&func, Targs &&... args) {
std::forward<Tfunc>(func)(std::forward<Targs>(args)...);
}
void value() {}
};
template <class Tfunc, class Tbefore, class Tafter>
auto decorate(Tfunc &&func, Tbefore &&before, Tafter &&after) {
return [
func = std::forward<Tfunc>(func),
before = std::forward<Tbefore>(before),
after = std::forward<Tafter>(after)
] (auto &&... args) -> decltype(auto) {
before(std::forward<decltype(args)>(args)...);
RetWrapper<std::result_of_t<Tfunc(decltype(args)...)>> ret(
func, std::forward<decltype(args)>(args)...
);
after(std::forward<decltype(args)>(args)...);
return ret.value();
};
}
/*
* Tests
*/
float test1(float a, float b) {
std::cout << "Inside test1\n";
return a * b;
}
void test2() {
std::cout << "Inside test2\n";
}
int i = 0;
int &test3() {
return i;
}
int main() {
auto test1Deco = decorate(
test1,
[] (float a, float b) {
std::cout << "Calling test1 with " << a << " and " << b << '\n';
},
[] (float a, float b) {
std::cout << "Called test1 with " << a << " and " << b << '\n';
}
);
float c = test1Deco(3.5f, 5.1f);
std::cout << "Yields " << c << '\n';
auto test2Deco = decorate(
test2,
[] () {
std::cout << "Calling test2\n";
},
[] () {
std::cout << "Called test2\n";
}
);
test2Deco();
auto test3Deco = decorate(
test3,
[] () {
std::cout << "Calling test3\n";
},
[] () {
std::cout << "Called test3\n";
}
);
auto &i2 = test3Deco();
i2 = 42;
std::cout << "Global i = " << i << '\n';
return 0;
}
Output :
Calling test1 with 3.5 and 5.1
Inside test1
Called test1 with 3.5 and 5.1
Yields 17.85
Calling test2
Inside test2
Called test2
Calling test3
Called test3
Global i = 42
Just go full template, without std::function:
template< typename Func >
class FunctionDecorator
{
public:
FunctionDecorator( Func func )
: m_func( std::move(func) )
{}
void operator()()
{
// do some stuff prior to function call
m_func();
// do stuff after function call
}
private:
Func m_func;
};
template< typename Func >
FunctionDecorator<Func> decorate(Func func) {
return FunctionDecorator<Func>(std::move(func));
}
[Note: edited a few hours after initial posting]
This perhaps isn't exactly what the OP was looking for, but it's still relevant and hopefully useful to others looking for answers.
Let's say you have a couple of functions that have slightly different signatures:
void foo1(int& x){ cout << "foo1(" << x << ")\n";}
void foo2(double& x){ cout << "foo2(" << x << ")\n";}
and you'd like to wrap a decorator around them both so as to standardise their signatures, e.g. turn them both into void (*)(int).
Then you could do the following:
template<typename Q, void (*foo_p)(Q&)>
void wrapped(int x){
Q v = 42.2 + x;
foo_p(v);
}
int main(){
using foo_t = void (*)(int); // we coerce foo1 and foo2 into this type
foo_t k_int = wrapped<int, foo1>;
foo_t k_double = wrapped<double, foo2>;
k_int(-1); //cout: foo1(41)
k_double(-1); //cout: foo2(41.2)
return 0;
}
Using the example main I've given here, clang inlines the whole thing, which is a good sign but not quite what we wanted to check. If you make the example a bit more complex (see live here) you can see that it does indeed inline everything within each wrapper, i.e. foo1 and foo2 don't exist in standalone form, only in wrapped form.
Originally, I use a lambda in addition to the wrapped<...> template (making use of the fact that lambdas with no-capture can be converted to function pointers) but then I realized that the extra wrapping was redundant in this case.
This method should work for passing anything known at run time, which could even include a pointer to a mutable global (although that's getting pretty messy).
#include <iostream>
#include <string>
using namespace std;
template <typename TResult, typename TParams>
class CClassGenerique
{
typedef TResult (*uneFonction) (TParams);
public :
CClassGenerique (uneFonction f){ m_function = f; }
void operator () (TParams t) { m_function (t); }
private :
uneFonction m_function;
};
template <typename TResult, typename TParams>
TResult BasicFunction (TParams p)
{
TResult t=0;
std::cout<<" Value = " << p <<endl;
return t;
}
int main (int argc, char* argv[])
{
CClassGenerique<int, int> c1 (BasicFunction<int, int>);
CClassGenerique<int, char*> c2 (BasicFunction<int, char*>);
CClassGenerique<char*, char*> c3 (BasicFunction<char*, char*>);
c1(3);
c2("bonsoir");
c3("hello");
return 0;
}
Related
Looking at this answer I can see how to call a pointer to a member function by explicitly passing in this. However, what if I want the function passed in to be a member of the current object and to use the implicit this.
I've written this, which seems to work, but is it valid code, and is there a better way (C++14 or below) avoiding the dynamic_cast<>? Source on onlinegdb.com
#include <iostream>
class Base
{
public:
// From https://stackoverflow.com/a/9779391/1270789
template<typename T, typename R>
R proxycall(T *obj, R (T::*mf)(int))
{
return (obj->*mf)(42);
}
// My attempt
template<typename T, typename R>
R proxycall(R (T::*mf)(int))
{
return ((dynamic_cast<T *>(this))->*mf)(42);
}
virtual ~Base() {}
};
class Foo: public Base
{
public:
int doFoo(int x) { std::cout << "doing foo\n"; return x / 2; }
int doCall() { return proxycall(this, &Foo::doFoo); } // OK
int doNoThisCall() { return proxycall(&Foo::doFoo); } // Is this OK?
};
int main()
{
Foo foo;
std::cout << foo.doCall() << '\n';
std::cout << foo.doNoThisCall() << '\n';
return 0;
}
I am writing a library for thread management using C++ for my app and as part of the same I am trying to write a template class that takes a FunctionPointer to be executed inside the run function. I am a Java developer and trying to visualize as follows:
class MyRunnable : public Runnable {
public:
MyRunnable(fp)
{
mFp = fp;
}
private:
FunctionPointer mFp;
// Will be called by the thread pool using a thread
void run()
{
mFp();
}
}
class ThreadManager {
public:
void execute(MyRunnable runnable) {
executeOnAThreadPool(runnable);
}
}
Since I am not fluent with C++ syntax, I am finding hard to get the constructor defined to take a FunctionPointer as argument with variable number of arguments for the FunctionPointer. Something like:
MyRunnable(Fp fp, Args... args)
Can someone please help me defining the constructor for MyRunnable class above.
Thanks.
Not sure... but seems to me that you're looking something as
class MyRunnable
{
private:
std::function<void()> mF;
public:
template <typename F, typename ... Args>
MyRunnable (F && f, Args && ... args)
: mF{ [&f, &args...](){ std::forward<F>(f)(std::forward<Args>(args)...); } }
{ }
void run ()
{ mF(); }
};
The following is a full compiling example
#include <iostream>
#include <functional>
class MyRunnable
{
private:
std::function<void()> mF;
public:
template <typename F, typename ... Args>
MyRunnable (F && f, Args && ... args)
: mF{ [&f, &args...](){ std::forward<F>(f)(std::forward<Args>(args)...); } }
{ }
void run ()
{ mF(); }
};
void foo (int a, long b, std::string const & c)
{ std::cout << "executing foo() with " << a << ", " << b << ", " << c << '\n'; }
int main ()
{
MyRunnable mr{foo, 1, 2l, "three"};
std::cout << "before run" << '\n';
mr.run();
}
that prints
before run
executing foo() with 1, 2, three
Is it possible to rebind a std::function to point to the same function but with a different object instance?
Say if I have an object that has a std::function that is bound to another function, but if that object was copied to another instance, I'd like to rebind the std::function to that new instance instead of the old instance.
#include "stdafx.h"
#include <iostream>
#include <functional>
class EventHandler
{
public:
int Num;
std::function<int()> OnEvent;
EventHandler (int inNum)
{
Num = inNum;
}
EventHandler (const EventHandler& other)
{
Num = other.Num;
OnEvent = other.OnEvent; //TODO: Need some way to redirect the std::function to the new instance rather than having the delegate point to the original object's handler.
}
int HandleEvent ()
{
return Num;
}
};
int main()
{
EventHandler a(4);
a.OnEvent = std::bind(&EventHandler::HandleEvent, a);
EventHandler b(a);
b.Num = 5;
//Uncommenting the line below is a manual way of redirecting event handler to the new instance.
//b.OnEvent = std::bind(&EventHandler::HandleEvent, b);
int aResult = a.OnEvent();
int bResult = b.OnEvent();
//This will print out 4 and 4 instead of 4 and 5 since b is still bound to a's event handler.
std::cout << "aResult=" << aResult << " bResult=" << bResult << '\n';
return 0;
}
I'm open to having a wrapper of the std::function to store additional information.
The following code introduced a binding_function<R(Args...)>, which is called like function<R()>, and arguments can be rebind anytime after it constructed (assuming it was not nullptr).
#include <functional>
#include <tuple>
#include <utility>
#include <memory>
#include <iostream>
template <typename T>
class binding_function;
template <typename R, typename... Args>
class binding_function<R(Args...)> : std::function<R()>
{
using base_function = std::function<R(Args...)>;
using binded_function = std::function<R()>;
base_function base;
public:
binding_function() = default;
template <typename BaseF, typename... TArgs>
binding_function(BaseF&& f, TArgs&&... args)
: base(std::forward<BaseF>(f)) {
rebind(std::forward<TArgs>(args)...);
}
template <typename... TArgs>
void rebind(TArgs&&... args)
{
static_cast<binded_function&>(*this) =
std::bind(base, std::forward<TArgs>(args)...);
}
using binded_function::operator();
};
class EventHandler
{
public:
// change type of OnEvent to binding_function
binding_function<int(EventHandler)> OnEvent;
// others remain the same
};
int main()
{
EventHandler a(4);
// first binding
a.OnEvent = {&EventHandler::HandleEvent, a};
EventHandler b(a);
b.Num = 5;
b.OnEvent.rebind(b); // rebinding
int aResult = a.OnEvent();
int bResult = b.OnEvent();
//This will print out 4 and 4 instead of 4 and 5 since b is still bound to a's event handler.
std::cout << "aResult=" << aResult << " bResult=" << bResult << '\n';
return 0;
}
What your event handler does should depend on which instance it is called on. Hence, logically, the correct way of solving the problem is providing the instance as a parameter to the handler function, e.g.
#include <iostream>
#include <functional>
class EventHandler
{
private:
std::function<int(EventHandler &)> handlingFunction;
public:
int Num;
EventHandler (int inNum)
: handlingFunction ([] (EventHandler &) -> int { throw 0; })
, Num (inNum)
{ }
void SetHandlingFunction (std::function<int(EventHandler &)> f) {
handlingFunction = f;
}
// for convenience, if the handling function is a member
void SetHandlingFunction (int EventHandler::*mf ()) {
handlingFunction =
[mf] (EventHandler & myself) -> int { return myself.*mf (); }
;
}
int OnEvent () {
return handlingFunction (*this);
}
int HandleEvent ()
{
return Num;
}
};
int main()
{
EventHandler a(4);
a.SetHandlingFunction ( [] (EventHandler & h) -> int { return h.HandleEvent (); } );
// or
a.SetHandlingFunction (&EventHandler::HandleEvent);
EventHandler b(a);
b.Num = 5;
int aResult = a.OnEvent();
int bResult = b.OnEvent();
std::cout << "aResult=" << aResult << " bResult=" << bResult << '\n';
return 0;
}
Of course, if your handling function always is a member function, you can simply replace the std::function by a pointer-to-member-function.
Note that you should properly initialize the handlingFunction member in the constructor of your EventHandler class, e.g. by setting it to a dummy function.
I extended user1887915's answer to allow functions with parameters:
#include <functional>
#include <tuple>
#include <utility>
#include <memory>
#include <iostream>
template <typename T>
class binding_function;
template <typename R, typename... Args, typename SelfType>
class binding_function<R(SelfType, Args...)> : std::function<R(Args...)>
{
using base_function = std::function<R(SelfType, Args...)>;
using binded_function = std::function<R(Args...)>;
base_function base;
public:
binding_function() = default;
template <typename BaseF, typename... TArgs>
binding_function(BaseF&& f, SelfType t, TArgs&&... args)
: base(std::forward<BaseF>(f)) {
rebind(std::forward<SelfType>(t), std::forward<TArgs>(args)...);
}
template <typename T, typename... TArgs>
void rebind(T&& t, TArgs&&... args)
{
static_cast<binded_function&>(*this) =
std::bind(base, std::forward<SelfType>(t), std::forward<TArgs>(args)...);
}
using binded_function::operator();
};
class EventHandler
{
public:
int Num;
binding_function<int(EventHandler, int)> OnEvent;
EventHandler (int inNum)
{
Num = inNum;
}
EventHandler (const EventHandler& other)
{
Num = other.Num;
OnEvent = other.OnEvent; //TODO: Need some way to redirect the std::function to the new instance rather than having the delegate point to the original object's handler.
}
int HandleEvent (int value)
{
return Num + value;
}
};
int main()
{
EventHandler a(4);
// first binding
a.OnEvent = {&EventHandler::HandleEvent, a, std::placeholders::_1};
EventHandler b(a);
b.Num = 5;
b.OnEvent.rebind(b, std::placeholders::_1); // rebinding
int aResult = a.OnEvent(1);
int bResult = b.OnEvent(1);
//This will print out 4 and 4 instead of 4 and 5 since b is still bound to a's event handler.
std::cout << "aResult=" << aResult << " bResult=" << bResult << '\n';
return 0;
}
AFAIK what you are asking is not possible, but I think there is a workaround that you can do:
class EventHandler
{
public:
int Num;
std::function<int()> OnEvent;
template <typename Func>
EventHandler (int inNum, Func on_event)
{
Num = inNum;
OnEvent = [=]() { return (this->*on_event)(); };
}
EventHandler (const EventHandler& other): EventHandler(other.Num, &EventHandler::HandleEvent) {}
int HandleEvent ()
{
return Num;
}
};
int main()
{
EventHandler a(4, &EventHandler::HandleEvent);
EventHandler b(a);
b.Num = 5;
int aResult = a.OnEvent();
int bResult = b.OnEvent();
//This will print out 4 and 4 instead of 4 and 5 since b is still bound to a's event handler.
std::cout << "aResult=" << aResult << " bResult=" << bResult << '\n';
return 0;
}
This prints "aResult=4 bResult=5" as you want.
Also, I think by employing a bit more metaprogramming magic, we can try to prettify the syntax.
Let me know if this works for you.
Can I do something like this?
template<function_pointer_type pointer_name> struct structure1{
//here I call pointer_name(0)
};
void* function1 = [&](int a) {
return a * a;
}
structure1<function1> b;
I tried but it never compiled.
So, what's wrong with the code?
function1 is not constant expression so it cannot be used as template argument.
The lambda is not convertible to function pointer because it has a non-empty capture list.
Instead of function pointer, I suggest using a template parameter of function object, or std::function.
Function object:
template <class FunctionObject>
class A
{
private:
FunctionObject fun;
public:
A(FunctionObject f) : fun(f) {}
void f() { cout << fun(5) << endl; }
};
template <class FunctionObject>
A<FunctionObject> make_A(FunctionObject f)
{
return A<FunctionObject>(f);
}
std::function:
template <class FunctionType>
struct B
{
std::function<FunctionType> fun;
};
The usage:
void usage()
{
auto a = make_A([](int a) {return a*a; });
a.f();
B<int(int)> b;
b.fun = [&](int a) {return a*a; };
cout << b.fun(10) << endl;
}
To make this as absolutely similar to your original question as possible (using a lambda and a templated structure and so on):
#include <iostream>
template<typename F>
struct structure1 {
structure1(F x) : f(x) {}
int operator() (int a) { return f(a); };
F f;
};
int(*function1)(int) = [&](int a) {
return a * a;
};
int main() {
structure1< int(*)(int) > x(function1);
std::cout << x(4) << std::endl;
return 0;
}
I compiled and tested this with g++ -std=c++11 test.cpp
I have a such factories, which instantiate objects by passed template class name T:
template<class T>
class Factory0
{
public:
static void *Create(){ return new T(); }
};
template<class T, class Argument1>
class Factory1
{
public:
static void *Create( Argument1 &arg1 ){ return new T( arg1 ); }
};
And i need to do something like such:
map<string[ClassName], &factory] _builder;
...
template<class T>
Add(){
if( T derived from BaseClass ) _builder[T] = &factory1::Create
else if( T derived from BaseClass ) _builder[T] = &factory0::Create;
}
template<class T>
Create() {
return _builder[T]( (factory0) ? <nothing> : <some_argument> );
}
This is hard for two reasons:
Calling create with the wrong arguments can only be caught at runtime, so we need a bit of dynamic typing.
C++ really doesn't like casting function pointers. Or creating pointers to templated functions. Or generally doing anything complex with function pointers.
But it can be done:
#include<string>
#include<map>
#include<iostream>
using namespace std;
struct returnable {
// Put some interesting virtual functions here
};
struct foo : public returnable {
foo() {
cout << "defaulFoo" << endl;
}
foo(int x) {
cout << "Foo:" << x << endl;
}
};
struct bar : public returnable {
bar(char a, char b){
cout << "bar:" << a << "," << b << endl;
}
};
template<typename... ARGS>
struct newmakerbase {
virtual returnable* make(ARGS... args) = 0;
};
template<typename OUT, typename... ARGS>
struct newmaker : public newmakerbase<ARGS...> {
virtual returnable* make(ARGS... args) {
return new OUT(args...);
}
};
// Boost might provide a neater version of this
int nextId = 0;
template<typename... T>
struct typeId {
static const int id;
};
template<typename... T>
const int typeId<T...>::id = nextId++;
map<string,void*> builders;
map<string,int> argtypes;
template<typename OUT, typename... ARGS>
void registerClas(string name) {
builders[name] = static_cast<void*>(new newmaker<OUT,ARGS...>());
argtypes[name] = typeId<ARGS...>::id;
}
template<typename... ARGS>
returnable* create(string name, ARGS... args) {
int argsgiven = typeId<ARGS...>::id;
if (argsgiven != argtypes[name]) {
// TODO: maybe throw an exception or something?
return NULL;
}
newmakerbase<ARGS...>* builder = static_cast<newmakerbase<ARGS...>*>(builders[name]);
return builder->make(args...);
}
main() {
registerClas<foo>("defaultFoo");
registerClas<foo,int>("foo");
registerClas<bar,char,char>("bar");
returnable* a = create("defaultFoo");
returnable* b = create("foo", 42);
returnable* c = create("foo", 'a', 'b'); // returns NULL
returnable* d = create("foo", 42.0); // also returns NULL
returnable* e = create("bar", 'c', 'd');
cout << a << " " << b << " " << c << " " << d << " " << e << endl;
}