Opposite of std::bind, add dummy parameters to function - c++

I need something that is the opposite of std::bind, that adds dummy parameters to a function signature instead of how boost::bind binds parameters away.
e.g. I have this function:
std::function<void (void)> myFunc;
But I want to convert it into a std::function<void(int)> to pass into this function
void processFunction( std::function<void(int)> func);

Edit Oh, I mentioned the obvious in chat:
#EthanSteinberg: lambdas?
[] (int realparam, int dummy) { return foo(realparam); }
But it was dismissed, which is why I jump to:
Edit I just realized a much simpler approach: http://ideone.com/pPWZk
#include <iostream>
#include <functional>
using namespace std::placeholders;
int foo(int i)
{
return i*2;
}
int main(int argc, const char *argv[])
{
std::function<int(int, int)> barfunc = std::bind(foo, (_1, _2));
std::cout << barfunc(-999, 21) << std::endl;
// or even (thanks Xeo)
barfunc = std::bind(foo, _2);
std::cout << barfunc(-999, 21) << std::endl;
}
Variadic Templates http://ideone.com/8KIsW
A somewhat longer answer based on variadic templates would result in possibly smaller code at the call site (if you wanted to wrap functions with a long argument list).
#include <iostream>
#include <functional>
int foo(int i)
{
return i*2;
}
template <typename Ax, typename R, typename... A>
struct Wrap
{
typedef R (*F)(A...);
typedef std::function<R(A...)> Ftor;
Wrap(F f) : _f(f) { }
Wrap(const Ftor& f) : _f(f) { }
R operator()(Ax extra, A... a) const
{ return _f(a...); /*just forward*/ }
Ftor _f;
};
template <typename Ax=int, typename R, typename... A>
std::function<R(Ax, A...)> wrap(R (f)(A...))
{
return Wrap<Ax,R,A...>(f);
}
template <typename Ax=int, typename R, typename... A>
std::function<R(Ax, A...)> wrap(std::function<R(A...)> functor)
{
return Wrap<Ax,R,A...>(functor);
}
int main(int argc, const char *argv[])
{
auto bar = wrap(foo);
std::function<int(int, int)> barfunc = wrap(foo);
std::cout << barfunc(-999, 21) << std::endl;
// wrap the barfunc?
auto rewrap = wrap(barfunc);
std::cout << rewrap(-999, -999, 21) << std::endl;
return 0;
}
Generalizing from this would require some more heavy lifting. I think I've seen in the past helpers to 'dissect' (using meta-programming) the signature of a std::function<> and you should be able to make it recognize non-void functions, and perhaps even adding a parameter at the end or in the middle (tricky, as far as I can tell now).
But for your simple case from the OP, it looks like you're covered

You could use a lambda, if your implementation supports it:
processFunction([=](int a){ myFunc(); });

Related

Generating lambda from class template

I have a class that registers callback functions and calls them later that looks like this.
template<typename ReturnType, typename... Args>
class Signal {
std::vector<std::function<ReturnType(Args...)>> function;
public:
template<typename... Args2>
ReturnType operator()(Args2&&... args2) {
ReturnType ret;
for (auto& func : function)
ret = func(std::forward<Args2>(args2)...);
return ret;
}
template<typename Func>
void func(Func const &func) {
function.push_back(std::function<ReturnType(Args...)>(func));
}
template<typename Class, typename Instance>
void mfunc(ReturnType(Class::*func)(Args...), Instance &instance) {
mfunc2(func, instance, make_int_sequence<sizeof...(Args)>{});
}
template<typename Class, typename Instance, int... I>
void mfunc2(ReturnType(Class::*func)(Args...), Instance &instance, int_sequence<I...>) {
using namespace std::placeholders;
function.push_back(std::function<ReturnType(Args...)>(std::bind(func, &instance, placeholder_template<I>{}...)));
}
};
#include <iostream>
class foo {
public:
int bar(int x, double y) {
std::cout << x << " and " << y << std::endl;
return x*2;
}
};
int main() {
foo foo1;
Signal<int, int, double> sig;
sig.mfunc(&foo::bar, foo1);
std::cout << "Return: " << sig(5,5.5) << std::endl;
}
I heard a talk from Stephan T. Lavavej today, and one of the things he was saying is that std::bind should be avoided and use lambdas instead. So to learn something new I figured I would try and change the std::bind call in mfunc2 to a lambda, but I'm quite new to templates and can't figure out how to generate the code I want.
The current placeholder_template with make_int_sequence I found here on SO, but I can't really wrap my head around how exactly it works, or where to find any good reading on it...
Args... holds the argument types that should be accepted by the lambda, but I need to somehow create variable names such as var1, var2, var3 ect depending on the sizeof...(Args) and then merge them together.
So for example < int, int, int >, Args... would hold int, int.
I then want to construct the lambda as
[func, &instance](int var1, int var2) -> ReturnType { return func(&instance, var1, var2); }
How could I accomplish this?
This should do the job:
template<typename ReturnType, typename... Args>
class Signal {
std::vector<std::function<ReturnType(Args...)>> function;
public:
template<typename... Args2>
ReturnType operator()(Args2&&... args2) {
ReturnType ret;
for (auto& func : function)
ret = func(std::forward<Args2>(args2)...);
return ret;
}
template<typename Func>
void func(Func const &func) {
function.push_back(std::function<ReturnType(Args...)>(func));
}
template<typename Class, typename Instance>
void mfunc(ReturnType(Class::*func)(Args...), Instance& instance) {
function.push_back([&instance, func](Args&&... args) {
return (instance.*func)(std::forward<Args>(args)...);
});
}
};
https://ideone.com/gjPdWN
Note that in your operator(), you basically throw away all return values except the last one. Is that behaviour intended?

C++ function call wrapper with function as template argument

I'm trying to create a generic wrapper function that takes a function as a template argument and takes the same arguments as that function as its arguments. For example:
template <typename F, F func>
/* return type of F */ wrapper(Ts... Args /* not sure how to get Ts*/)
{
// do stuff
auto ret = F(std::forward<Ts>(args)...);
// do some other stuff
return ret;
}
The solution needs to be castable to a function pointer with the same type as func so that I can pass it to a C api. In other words, the solution needs to be a function and not a function object. Most importantly, I need to be able to do work in the wrapper function.
If the inline comments aren't clear, I'd like to be able to do something like the following:
struct c_api_interface {
int (*func_a)(int, int);
int (*func_b)(char, char, char);
};
int foo(int a, int b)
{
return a + b;
}
int bar(char a, char b, char c)
{
return a + b * c;
}
c_api_interface my_interface;
my_interface.func_a = wrapper<foo>;
my_interface.func_b = wrapper<bar>;
I looked for related posts and found these, but none of them are quite what I'm trying to do. Most of these posts concern function objects. Is what I'm trying to do even possible?
Function passed as template argument
Function wrapper via (function object) class (variadic) template
How does wrapping a function pointer and function object work in generic code?
How do I get the argument types of a function pointer in a variadic template class?
Generic functor for functions with any argument list
C++ Functors - and their uses
In response to the first 2 responses, I edited the question to make it clear that I need to be able to do work in the wrapper function (i.e. modify some global state before and after the call to the wrapped function)
template<class F, F f> struct wrapper_impl;
template<class R, class... Args, R(*f)(Args...)>
struct wrapper_impl<R(*)(Args...), f> {
static R wrap(Args... args) {
// stuff
return f(args...);
}
};
template<class F, F f>
constexpr auto wrapper = wrapper_impl<F, f>::wrap;
Use as wrapper<decltype(&foo), foo>.
#include <utility>
#include <iostream>
struct c_api_interface { int (*func_a)(int, int); int (*func_b)(char, char, char); };
int foo(int a, int b) { return a + b; }
int bar(char a, char b, char c) { return a + b * c; }
template<typename Fn, Fn fn, typename... Args>
typename std::result_of<Fn(Args...)>::type
wrapper(Args... args) {
std::cout << "and ....it's a wrap ";
return fn(std::forward<Args>(args)...);
}
#define WRAPIT(FUNC) wrapper<decltype(&FUNC), &FUNC>
int main() {
c_api_interface my_interface;
my_interface.func_a = WRAPIT(foo);
my_interface.func_b = WRAPIT(bar);
std:: cout << my_interface.func_a(1,1) << std::endl;
std:: cout << my_interface.func_b('a','b', 1) << std::endl;
return 0;
}
see http://rextester.com/ZZD18334
you may try something like that (Ugly, but works)
#include <iostream>
#include <functional>
struct wrapper_ctx
{
wrapper_ctx ()
{
std::cout << "Before" << std::endl;
}
~wrapper_ctx ()
{
std::cout << "after" << std::endl;
}
};
template <typename F, typename... Args>
auto executor (F&& f, Args&&... args) -> typename std::result_of<F(Args...)>::type
{
wrapper_ctx ctx;
return std::forward<F>(f)( std::forward<Args>(args)...);
}
template <typename F>
class wrapper_helper;
template<typename Ret, typename... Args>
class wrapper_helper <std::function<Ret(Args...)>>
{
std::function<Ret(Args...)> m_f;
public:
wrapper_helper( std::function<Ret(Args...)> f )
: m_f(f) {}
Ret operator()(Args... args) const
{
return executor (m_f, args...);
}
};
template <typename T>
wrapper_helper<T> wrapper (T f)
{
return wrapper_helper <T>(f);
}
int sum(int x, int y)
{
return x + y;
}
int main (int argc, char* argv [])
{
std::function<int(int, int)> f = sum;
auto w = wrapper (f);
std::cout << "Executing the wrapper" << std::endl;
int z = w(3, 4);
std::cout << "z = " << z << std::endl;
}
you probably need something like
template <typename F>
class Wrapper {
public:
Wrapper(F *func) : function(func) {}
operator F* () { return function; }
F *function;
};
Which you can use like void (*funcPtr)(int) = Wrapper<void(int)>(&someFunction);
I think that will be the concise way to do what you want:
template <typename F>
F* wrapper(F* pFunc)
{
return pFunc;
}
and use it like this:
my_interface.func_a = wrapper(foo);
my_interface.func_a(1, 3);
You may try this
template <class R, class... Args>
struct wrap
{
using funct_type = R(*)(Args...);
funct_type func;
wrap(funct_type f): func(f) {};
R operator()(Args&&... args)
{
//before code block
std::cout << "before calling\n";
R ret=func(std::forward<Args>(args)...);
//after code block
std::cout << "After calling\n";
}
};
use like this for example:
int somefunc(double &f, int x);
auto wrapped_somefunc=wrap{somefunc};
double f=1.0;
int x = 2;
auto result=wrapped_somefunc(f,x);
This one is for c++17 and newer uses auto template parameters:
template <auto func, class... Args>
auto wrap_func(Args... args)
{
std::cout << "before calling wrapped func\n";
auto ret = func(args...);
std::cout << "after calling wrapped func\n";
return ret;
}
use for example:
int some_func(int a, int b);
auto ret = wrap_func<some_func>(2, 3);

How to call a function several times in C++ with different parameters

I have the next code:
object a,b,c;
fun (a);
fun (b);
fun (c);
I wonder if it is there any way to do something similar in C++98 or C++11 to:
call_fun_with (fun, a, b, c);
Thanks
Here a variadic template solution.
#include <iostream>
template < typename f_>
void fun( f_&& f ) {}
template < typename f_, typename head_, typename... args_>
void fun( f_ f, head_&& head, args_&&... args) {
f( std::forward<head_>(head) );
fun( std::forward<f_>(f), std::forward<args_>(args)... );
}
void foo( int v ) {
std::cout << v << " ";
}
int main() {
int a{1}, b{2}, c{3};
fun(foo, a, b, c );
}
You may use the following using variadic template:
template <typename F, typename...Ts>
void fun(F f, Ts&&...args)
{
int dummy[] = {0, (f(std::forward<Ts>(args)), 0)...};
static_cast<void>(dummy); // remove warning for unused variable
}
or in C++17, with folding expression:
template <typename F, typename...Ts>
void fun(F&& f, Ts&&...args)
{
(static_cast<void>(f(std::forward<Ts>(args))), ...);
}
Now, test it:
void foo(int value) { std::cout << value << " "; }
int main(int argc, char *argv[])
{
fun(foo, 42, 53, 65);
return 0;
}
Using C++ 11, you can use std::function, this way (which is quite quick to write IMO)
void call_fun_with(std::function<void(int)> fun, std::vector<int>& args){
for(int& arg : args){
fun(arg);
}
}
or, a bit more generic:
template<typename FTYPE>
void call_fun_with(FTYPE fun, std::vector<int>& args){
for(int& arg : args){
fun(arg);
}
}
Live example
Live example, templated version
Note: std::function template arguments must be specified the following way: return_type(arg1_type, arg2_type,etc.)
EDIT: An alternative could be using std::for_each which actually does pretty much the same thing, but which I do not really like as to the semantics, which are more like "for everything in this container, do...". But that's just me and my (maybe silly) way of coding :)
A C++11 range-based (enhanced) for loop will recognise a braced-init-list as an initializer_list, which means something like the following will work:
for (auto &x : {a,b,c}) fun(x);
there are a lot of different way's...
#include <iostream>
#include <vector>
#include <algorithm>
void foo(int x) {
std::cout << x << "\n";
}
void call_fun_with(std::function<void(int)> fn, std::vector<int> lst) {
for(auto it : lst)
fn(it);
}
int main() {
std::vector<int> val = {1,2,3,4,5};
// c++98
std::for_each(val.begin(), val.end(), foo);
// c++11
// vector
call_fun_with(foo, val);
// c++11
// initializer_list
int a=0, b=1, c=2;
call_fun_with(foo, {a,b,c});
}
see here.

Workaround to allow tr1::function to swallow return values

As a follow-up to Can tr1::function swallow return values?, how can one work around the limitation that tr1::function cannot swallow return values?
This should work in the specific case of swallowing the return value of a callable object taking no arguments:
template<typename FuncT>
struct swallow_return_t
{
explicit swallow_return_t(FuncT i_Func):m_Func(i_Func){}
void operator()(){ m_Func(); }
FuncT m_Func;
};
template<typename FuncT>
swallow_return_t<FuncT>
swallow_return(FuncT f)
{
return swallow_return_t<FuncT>(f);
}
Then use like:
int Foo();
std::tr1::function<void()> Bar = swallow_return(Foo);
I assume variadic templates and perfect forwarding would permit generalization of this technique to arbitrary parameter lists. Is there a better way?
The following works for me in GCC 4.6.1:
#include <functional>
int foo() { return 5; }
int goo(double, char) { return 5; }
int main()
{
std::function<void()> f = foo;
std::function<void(float, int)> g = goo;
(void)f();
(void)g(1.0f, 'a');
}
Here's a wrapper using lambdas, but it's not automagic yet
template <typename T, typename ...Args>
struct strip_return
{
static inline std::function<void(Args...)> make_function(std::function<T(Args...)> f)
{
return [&f](Args... args) -> void { f(args...); };
}
};
int main()
{
auto q = strip_return<int>::make_function(std::bind(foo));
q();
}
Forget the middle part. OK, since std::function is type-erasing, it's hard to get at the underlying types. However, if you go for the function reference directly, you can avoid these problems entirely:
template <typename T, typename ...Args>
static inline std::function<void(Args...)> make_direct(T (&f)(Args...))
{
return [&f](Args... args) -> void { f(args...); };
}
int main()
{
auto p = make_direct(foo);
q();
}

C++ how to generalize class function parameter to handle many types of function pointers?

I do not know if what I am asking is doable, stupid or simple.
I've only recently started dwelling in template functions and classes, and I was wondering if the following scenario is possible:
A class which holds a function pointer to be called. The function pointer cannot be specific, but abstract, so that whenever the class's Constructor is called, it may accept different kinds of function pointers. When the class's execute function is called, it executes the function pointer allocated at construction, with an argument (or arguments).
Basically the abstraction is kept throughout the design, and left over the user on what function pointer and arguments to pass. The following code has not been tested, just to demonstrate what I'm trying to do:
void (*foo)(double);
void (*bar)(double,double);
void (*blah)(float);
class Instruction
{
protected:
double var_a;
double var_b;
void (*ptr2func)(double);
void (*ptr2func)(double,double);
public:
template <typename F> Instruction(F arg1, F arg2, F arg3)
{
Instruction::ptr2func = &arg1;
var_a = arg2;
var_b = arg3;
};
void execute()
{
(*ptr2func)(var_a);
};
};
I do not like the fact I have to keep a list inside the class of possible overloadable function pointers. How could I possibly improve the above to generalize it as much as possible so that it can work with any kind of function pointer thrown at it ?
Bear in mind, I will want to keep a container of those instantiated objects and execute each function pointer in sequence.
Thank you !
Edit: Maybe the class should be a template it'self in order to facilitate use with many different function pointers?
Edit2: I found a way around my problem just for future reference, don't know if it's the right one, but it works:
class Instruction
{
protected:
double arg1,arg2,arg3;
public:
virtual void execute() = 0;
};
template <class F> class MoveArm : public Instruction
{
private:
F (func);
public:
template <typename T>
MoveArm(const T& f,double a, double b)
{
arg1 = a;
arg2 = b;
func = &f;
};
void execute()
{
(func)(arg1,arg2);
};
};
However when importing functions, their function pointers need to be typedef'd:
void doIt(double a, double b)
{
std::cout << "moving arm at: " << a << " " << b << std::endl;
};
typedef void (*ptr2func)(double,double);
int main(int argc, char **argv) {
MoveArm<ptr2func> arm(doIt,0.5,2.3);
arm.execute();
return 0;
}
If you can use C++0x and variadic templates, you can achieve this by using combination of std::function, std::bind and perfect forwarding:
#include <iostream>
#include <functional>
template <typename Result = void>
class instruction
{
public:
template <typename Func, typename... Args>
instruction(Func func, Args&&... args)
{
m_func = std::bind(func, std::forward<Args>(args)...);
}
Result execute()
{
return m_func();
}
private:
std::function<Result ()> m_func;
};
double add(double a, double b)
{
return (a + b);
}
int main()
{
instruction<double> test(&add, 1.5, 2.0);
std::cout << "result: " << test.execute() << std::endl;
}
Example with output: http://ideone.com/9HYWo
In C++ 98/03, you'd unfortunately need to overload the constructor for up-to N-paramters yourself if you need to support variable-number of arguments. You'd also use boost::function and boost::bind instead of the std:: equivalents. And then there's also the issue of forwarding problem, so to do perfect forwarding you'd need to do an exponential amount of overloads depending on the amount of arguments you need to support. Boost has a preprocessor library that you can use to generate the required overloads without having to write all the overloads manually; but that is quite complex.
Here's an example of how to do it with C++98/03, assuming the functions you pass to the instruction won't need to take the arguments by modifiable reference, to do that, you also need to have overloads for P1& p1 instead of just const P1& p1.
#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>
template <typename Result = void>
class instruction
{
public:
template <typename Func>
instruction(Func func)
{
m_func = func;
}
template <typename Func, typename P1>
instruction(Func func, const P1& p1)
{
m_func = boost::bind(func, p1);
}
template <typename Func, typename P1, typename P2>
instruction(Func func, const P1& p1, const P2& p2)
{
m_func = boost::bind(func, p1, p2);
}
template <typename Func, typename P1, typename P2, typename P3>
instruction(Func func, const P1& p1, const P2& p2, const P3& p3)
{
m_func = boost::bind(func, p1, p2, p3);
}
Result execute()
{
return m_func();
}
private:
boost::function<Result ()> m_func;
};
double add(double a, double b)
{
return (a + b);
}
int main()
{
instruction<double> test(&add, 1.5, 2.0);
std::cout << "result: " << test.execute() << std::endl;
}
Example: http://ideone.com/iyXp1
I also created a C++0x version with some example usage. You can probably better use the one given by reko_t but I nevertheless post this one. This one uses recursion to unpack a tuple with values, and thus a tuple to store the arguments to pass to the function. Note that this one does not use perfect forwarding. If you use this, you probably want to add this.
#include <iostream>
#include <string>
#include <tuple>
using namespace std;
template<unsigned N>
struct FunctionCaller
{
template<typename ... Typenames, typename ... Args>
static void call(void (*func)(Typenames ...), tuple<Typenames ...> tuple, Args ... args)
{
FunctionCaller<N-1>::call(func, tuple, get<N-1>(tuple), args ...);
}
};
template<>
struct FunctionCaller<0u>
{
template<typename ... Typenames, typename ... Args>
static void call(void (*func)(Typenames ...), tuple<Typenames ...> tuple, Args ... args)
{
func(args ...);
}
};
template<typename ... Typenames>
class Instruction
{
public:
typedef void (*FuncType)(Typenames ...);
protected:
std::tuple<Typenames ...> d_args;
FuncType d_function;
public:
Instruction(FuncType function, Typenames ... args):
d_args(args ...),
d_function(function)
{
}
void execute()
{
FunctionCaller<sizeof...(Typenames)>::call(d_function, d_args);
}
};
void test1()
{
cout << "Hello World" << endl;
}
void test2(int a, string b, double c)
{
cout << a << b << c << endl;
}
int main(int argc, char** argv)
{
Instruction<> i1(test1);
Instruction<int, string, double> i2(test2, 5, "/2 = ", 2.5);
i1.execute();
i2.execute();
return 0;
}
Well, what you are doing is correct. But since all pointers have the same size in C++ you can store one pointer (of void type):
void *funcptr;
and cast it to the necessary type when needed:
static_cast<(*void)(double,double)>(funcptr)(var_a, var_b);
But please, only use this when better techniques can not be used, but I can not tell if you don't tell us the bigger picture.
You might want to look at boost::function.