how to call a function passed as argument with its parameters already given in D? - d

I need to call a function passed as argument to another function and it must be passed its needed arguments firstly. In c++, this problem is solved with a macro:
#include <iostream>
#define CALL(x) x; \
std::cout << "Called!" << std::endl;
void foo(int a, int b)
{
std::cout << a * b << std::endl;
}
int main()
{
CALL(foo(9, 8)); // I want to pass 2 int parameters inside 'foo' function call
system("PAUSE");
}
It sould output:
> 72
> Called!
That is exactly how I need to call the function in D. Any ideas?
Edit:
I need this to be done in D. I want to call "foo" inside CALL like:
CALL(foo(9, 8)) // and not like: CALL(foo, 9, 8)
But I don't know how this is achieved in D. Perhaps with a mixin?

In D, you can use a lazy function parameter for this.
import std.stdio;
void CALL(lazy void x) {
writeln("before called");
x;
writeln("after called");
}
void foo(int x, int y) {
writeln(x, " ", y);
}
void main() {
CALL(foo(3, 5));
}
D's lazy parameter storage class causes the compiler to wrap whatever you give it in a little anonymous function. The above is as if you wrote:
import std.stdio;
void CALL(void delegate() x) { // note delegate here in long-form syntax
writeln("before called");
x();
writeln("after called");
}
void foo(int x, int y) {
writeln(x, " ", y);
}
void main() {
// and this delegate too
CALL( delegate() { return foo(3, 5); } );
}
But the compiler rewrites it for you. This is why I said lazy void - the void there is the return type of the hidden function you pass. If it returned int, you could use lazy int instead.
Note that since x inside the CALL function is rewritten to be a hidden function, calling it twice will actually evaluate the arguments twice:
void CALL(lazy void x) {
writeln("before called");
x;
writeln("after called");
x;
writeln("after called again");
}
would do:
before called
3 5
after called
3 5
after called again
Notice how it printed out the arguments twice. Just like the C macro, actually. But if that's not what you want, simply assign it to a temporary yourself:
void CALL(lazy int x) {
auto tmp = x;
// you can now use tmp as a plain int
}

Related

Refactoring with AceButton Library causing "Invalid use of Non-Static member function" on compile [duplicate]

The question is the following: consider this piece of code:
#include <iostream>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
void function1(void (*function)(int, int))
{
function(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d", a , b , a - b);
}
int main()
{
aClass a;
function1(&test);
function1(&aClass::aTest); // <-- How should I point to a's aClass::test function?
}
How can I use the a's aClass::test as an argument to function1? I would like to access a member of the class.
There isn't anything wrong with using function pointers. However, pointers to non-static member functions are not like normal function pointers: member functions need to be called on an object which is passed as an implicit argument to the function. The signature of your member function above is, thus
void (aClass::*)(int, int)
rather than the type you try to use
void (*)(int, int)
One approach could consist in making the member function static in which case it doesn't require any object to be called on and you can use it with the type void (*)(int, int).
If you need to access any non-static member of your class and you need to stick with function pointers, e.g., because the function is part of a C interface, your best option is to always pass a void* to your function taking function pointers and call your member through a forwarding function which obtains an object from the void* and then calls the member function.
In a proper C++ interface you might want to have a look at having your function take templated argument for function objects to use arbitrary class types. If using a templated interface is undesirable you should use something like std::function<void(int, int)>: you can create a suitably callable function object for these, e.g., using std::bind().
The type-safe approaches using a template argument for the class type or a suitable std::function<...> are preferable than using a void* interface as they remove the potential for errors due to a cast to the wrong type.
To clarify how to use a function pointer to call a member function, here is an example:
// the function using the function pointers:
void somefunction(void (*fptr)(void*, int, int), void* context) {
fptr(context, 17, 42);
}
void non_member(void*, int i0, int i1) {
std::cout << "I don't need any context! i0=" << i0 << " i1=" << i1 << "\n";
}
struct foo {
void member(int i0, int i1) {
std::cout << "member function: this=" << this << " i0=" << i0 << " i1=" << i1 << "\n";
}
};
void forwarder(void* context, int i0, int i1) {
static_cast<foo*>(context)->member(i0, i1);
}
int main() {
somefunction(&non_member, nullptr);
foo object;
somefunction(&forwarder, &object);
}
#Pete Becker's answer is fine but you can also do it without passing the class instance as an explicit parameter to function1 in C++ 11:
#include <functional>
using namespace std::placeholders;
void function1(std::function<void(int, int)> fun)
{
fun(1, 1);
}
int main (int argc, const char * argv[])
{
...
aClass a;
auto fp = std::bind(&aClass::test, a, _1, _2);
function1(fp);
return 0;
}
A pointer to member function is different from a pointer to function. In order to use a member function through a pointer you need a pointer to it (obviously ) and an object to apply it to. So the appropriate version of function1 would be
void function1(void (aClass::*function)(int, int), aClass& a) {
(a.*function)(1, 1);
}
and to call it:
aClass a; // note: no parentheses; with parentheses it's a function declaration
function1(&aClass::test, a);
Since 2011, if you can change function1, do so, like this:
#include <functional>
#include <cstdio>
using namespace std;
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
template <typename Callable>
void function1(Callable f)
{
f(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d", a , b , a - b);
}
int main()
{
aClass obj;
// Free function
function1(&test);
// Bound member function
using namespace std::placeholders;
function1(std::bind(&aClass::aTest, obj, _1, _2));
// Lambda
function1([&](int a, int b) {
obj.aTest(a, b);
});
}
(live demo)
Notice also that I fixed your broken object definition (aClass a(); declares a function).
I asked a similar question (C++ openframeworks passing void from other classes) but the answer I found was clearer so here the explanation for future records:
it’s easier to use std::function as in:
void draw(int grid, std::function<void()> element)
and then call as:
grid.draw(12, std::bind(&BarrettaClass::draw, a, std::placeholders::_1));
or even easier:
grid.draw(12, [&]{a.draw()});
where you create a lambda that calls the object capturing it by reference
Important to note that unless you can change the signature of the code taking the function, there is no (easy) way to do this. That would be trying to implement a closure in a language that does not have closures that are the same as functions (the signature for a closure in C++ is different).
There are two actual ways to achieve this:
Use some sort of singleton/global variable that you store the closure in, and then pass a helper function that calls the needed function using that closure. Here is an example:
#include <stdio.h>
template<class C, typename ReturnType, typename... Args>
class ClosureSingleton {
typedef ReturnType (C::*FuncType)(Args...);
public:
static ClosureSingleton& getInstance() {
static ClosureSingleton instance;
return instance;
}
void setClosure(C* obj, FuncType f) {
this->obj = obj;
this->function = f;
}
static ReturnType funcPtr(Args... args) {
C* obj = getInstance().obj;
auto func = getInstance().function;
return (obj->*func)(args...);
}
private:
ClosureSingleton() {}
C* obj;
FuncType function;
public:
ClosureSingleton(ClosureSingleton const&) = delete;
void operator=(ClosureSingleton const&) = delete;
};
class aClass {
public:
void aTest1(int a, int b) { printf("%d + %d = %d\n", a, b, a + b); }
int aTest2(int a, int b) { return a + b; }
};
void function1(void (*function)(int, int)) {
function(1, 1);
}
int function2(int (*function)(int, int)) {
return function(1, 1);
}
int main() {
aClass tmp;
ClosureSingleton<aClass, void, int, int>::getInstance().setClosure(
&tmp, &aClass::aTest1);
function1(&ClosureSingleton<aClass, void, int, int>::funcPtr);
ClosureSingleton<aClass, int, int, int>::getInstance().setClosure(
&tmp, &aClass::aTest2);
printf(
"function2: %d\n",
function2(&ClosureSingleton<aClass, int, int, int>::funcPtr));
return 0;
}
Of course, this has the obvious downside that the closure needs to be set before every call, as well as some thread safety issues. Not ideal, but potentially workable in specific circumstances
Use something like asmjit or dynamic compilation to dynamically compile and pass the function in to the C code. This will only work on machines that allow heap section to be marked as executable. It is also very much non-portable as you will be writing assembly code to accomplish this. However, if you get it working, you will indeed have a true closure, albeit a substantially higher cost to creating the closure compared to how most programming languages implement closures (they do not duplicate the function assembly, instead they use a context object)
Patch the lib/dll that has the function handler to change it's signature to allow a context object. Again, a very brittle and non optimal solution.
My original answer, which does not really answer the question, but people found it useful:
Not sure why this incredibly simple solution has been passed up:
#include <stdio.h>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d\n", a, b, a + b);
}
};
template<class C>
void function1(void (C::*function)(int, int), C& c)
{
(c.*function)(1, 1);
}
void function1(void (*function)(int, int)) {
function(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d\n", a , b , a - b);
}
int main (int argc, const char* argv[])
{
aClass a;
function1(&test);
function1<aClass>(&aClass::aTest, a);
return 0;
}
Output:
1 - 1 = 0
1 + 1 = 2
I made the member function as static and all works:
#include <iostream>
class aClass
{
public:
static void aTest(int a, int b)
{
printf("%d + %d = %d\n", a, b, a + b);
}
};
void function1(int a,int b,void function(int, int))
{
function(a, b);
}
void test(int a,int b)
{
printf("%d - %d = %d\n", a , b , a - b);
}
int main (int argc, const char* argv[])
{
aClass a;
function1(10,12,test);
function1(10,12,a.aTest); // <-- How should I point to a's aClass::test function?
getchar();return 0;
}
If you actually don't need to use the instance a
(i.e. you can make it static like #mathengineer 's answer)
you can simply pass in a non-capture lambda. (which decay to function pointer)
#include <iostream>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
void function1(void (*function)(int, int))
{
function(1, 1);
}
int main()
{
//note: you don't need the `+`
function1(+[](int a,int b){return aClass{}.aTest(a,b);});
}
Wandbox
note: if aClass is costly to construct or has side effect, this may not be a good way.
You can stop banging your heads now. Here is the wrapper for the member function to support existing functions taking in plain C functions as arguments. thread_local directive is the key here.
http://cpp.sh/9jhk3
// Example program
#include <iostream>
#include <string>
using namespace std;
typedef int FooCooker_ (int);
// Existing function
extern "C" void cook_10_foo (FooCooker_ FooCooker) {
cout << "Cooking 10 Foo ..." << endl;
cout << "FooCooker:" << endl;
FooCooker (10);
}
struct Bar_ {
Bar_ (int Foo = 0) : Foo (Foo) {};
int cook (int Foo) {
cout << "This Bar got " << this->Foo << endl;
if (this->Foo >= Foo) {
this->Foo -= Foo;
cout << Foo << " cooked" << endl;
return Foo;
} else {
cout << "Can't cook " << Foo << endl;
return 0;
}
}
int Foo = 0;
};
// Each Bar_ object and a member function need to define
// their own wrapper with a global thread_local object ptr
// to be called as a plain C function.
thread_local static Bar_* Bar1Ptr = NULL;
static int cook_in_Bar1 (int Foo) {
return Bar1Ptr->cook (Foo);
}
thread_local static Bar_* Bar2Ptr = NULL;
static int cook_in_Bar2 (int Foo) {
return Bar2Ptr->cook (Foo);
}
int main () {
Bar1Ptr = new Bar_ (20);
cook_10_foo (cook_in_Bar1);
Bar2Ptr = new Bar_ (40);
cook_10_foo (cook_in_Bar2);
delete Bar1Ptr;
delete Bar2Ptr;
return 0;
}
Please comment on any issues with this approach.
Other answers fail to call existing plain C functions: http://cpp.sh/8exun

std::function and default function arguments

Here is simple example of using std::function
#include <iostream>
#include <functional>
//A function that sums two numbers.
//Arguments having default values.
void SumOfTwoNumbers(int a = 42, int b = 42)
{
std::cout << "Sum of two numbers :: " << a + b << std::endl;
}
int main()
{
std::function<void(int, int)> testFunc = SumOfTwoNumbers;
SumOfTwoNumbers(); //Works
testFunc(); //Compile time error
testFunc(40, 40); //Works
return 0;
}
In the main function, there are three function calls. The first one and the last one works. Whereas the second call testFunc() without any arguments gives compile time error.
Shouldn't it consider the default arguments and execute successfully?
No, the default values for function arguments are not part of the function signature. They are evaluated at the call site only.
You could use a lambda but then you'd need to redefine the default values:
auto testFunc = [](int a = 42, int b = 42) { SumOfTwoNumbers(a, b); };
... and storing such a lambda in a std::function would again result in the same problem since the signature of the lambda is also void(int, int).
You could however define your own wrapper functor (instead of using std::function) that has multiple operator() overloads:
struct {
void operator()() { SumOfTwoNumbers(42, 42); }
void operator()(int a) { SumOfTwoNumbers(a, 42); }
void operator()(int a, int b) { SumOfTwoNumbers(a, b); }
} testFunc;

How can I pass a function as a parameter in C++? [duplicate]

The question is the following: consider this piece of code:
#include <iostream>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
void function1(void (*function)(int, int))
{
function(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d", a , b , a - b);
}
int main()
{
aClass a;
function1(&test);
function1(&aClass::aTest); // <-- How should I point to a's aClass::test function?
}
How can I use the a's aClass::test as an argument to function1? I would like to access a member of the class.
There isn't anything wrong with using function pointers. However, pointers to non-static member functions are not like normal function pointers: member functions need to be called on an object which is passed as an implicit argument to the function. The signature of your member function above is, thus
void (aClass::*)(int, int)
rather than the type you try to use
void (*)(int, int)
One approach could consist in making the member function static in which case it doesn't require any object to be called on and you can use it with the type void (*)(int, int).
If you need to access any non-static member of your class and you need to stick with function pointers, e.g., because the function is part of a C interface, your best option is to always pass a void* to your function taking function pointers and call your member through a forwarding function which obtains an object from the void* and then calls the member function.
In a proper C++ interface you might want to have a look at having your function take templated argument for function objects to use arbitrary class types. If using a templated interface is undesirable you should use something like std::function<void(int, int)>: you can create a suitably callable function object for these, e.g., using std::bind().
The type-safe approaches using a template argument for the class type or a suitable std::function<...> are preferable than using a void* interface as they remove the potential for errors due to a cast to the wrong type.
To clarify how to use a function pointer to call a member function, here is an example:
// the function using the function pointers:
void somefunction(void (*fptr)(void*, int, int), void* context) {
fptr(context, 17, 42);
}
void non_member(void*, int i0, int i1) {
std::cout << "I don't need any context! i0=" << i0 << " i1=" << i1 << "\n";
}
struct foo {
void member(int i0, int i1) {
std::cout << "member function: this=" << this << " i0=" << i0 << " i1=" << i1 << "\n";
}
};
void forwarder(void* context, int i0, int i1) {
static_cast<foo*>(context)->member(i0, i1);
}
int main() {
somefunction(&non_member, nullptr);
foo object;
somefunction(&forwarder, &object);
}
#Pete Becker's answer is fine but you can also do it without passing the class instance as an explicit parameter to function1 in C++ 11:
#include <functional>
using namespace std::placeholders;
void function1(std::function<void(int, int)> fun)
{
fun(1, 1);
}
int main (int argc, const char * argv[])
{
...
aClass a;
auto fp = std::bind(&aClass::test, a, _1, _2);
function1(fp);
return 0;
}
A pointer to member function is different from a pointer to function. In order to use a member function through a pointer you need a pointer to it (obviously ) and an object to apply it to. So the appropriate version of function1 would be
void function1(void (aClass::*function)(int, int), aClass& a) {
(a.*function)(1, 1);
}
and to call it:
aClass a; // note: no parentheses; with parentheses it's a function declaration
function1(&aClass::test, a);
Since 2011, if you can change function1, do so, like this:
#include <functional>
#include <cstdio>
using namespace std;
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
template <typename Callable>
void function1(Callable f)
{
f(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d", a , b , a - b);
}
int main()
{
aClass obj;
// Free function
function1(&test);
// Bound member function
using namespace std::placeholders;
function1(std::bind(&aClass::aTest, obj, _1, _2));
// Lambda
function1([&](int a, int b) {
obj.aTest(a, b);
});
}
(live demo)
Notice also that I fixed your broken object definition (aClass a(); declares a function).
I asked a similar question (C++ openframeworks passing void from other classes) but the answer I found was clearer so here the explanation for future records:
it’s easier to use std::function as in:
void draw(int grid, std::function<void()> element)
and then call as:
grid.draw(12, std::bind(&BarrettaClass::draw, a, std::placeholders::_1));
or even easier:
grid.draw(12, [&]{a.draw()});
where you create a lambda that calls the object capturing it by reference
Important to note that unless you can change the signature of the code taking the function, there is no (easy) way to do this. That would be trying to implement a closure in a language that does not have closures that are the same as functions (the signature for a closure in C++ is different).
There are two actual ways to achieve this:
Use some sort of singleton/global variable that you store the closure in, and then pass a helper function that calls the needed function using that closure. Here is an example:
#include <stdio.h>
template<class C, typename ReturnType, typename... Args>
class ClosureSingleton {
typedef ReturnType (C::*FuncType)(Args...);
public:
static ClosureSingleton& getInstance() {
static ClosureSingleton instance;
return instance;
}
void setClosure(C* obj, FuncType f) {
this->obj = obj;
this->function = f;
}
static ReturnType funcPtr(Args... args) {
C* obj = getInstance().obj;
auto func = getInstance().function;
return (obj->*func)(args...);
}
private:
ClosureSingleton() {}
C* obj;
FuncType function;
public:
ClosureSingleton(ClosureSingleton const&) = delete;
void operator=(ClosureSingleton const&) = delete;
};
class aClass {
public:
void aTest1(int a, int b) { printf("%d + %d = %d\n", a, b, a + b); }
int aTest2(int a, int b) { return a + b; }
};
void function1(void (*function)(int, int)) {
function(1, 1);
}
int function2(int (*function)(int, int)) {
return function(1, 1);
}
int main() {
aClass tmp;
ClosureSingleton<aClass, void, int, int>::getInstance().setClosure(
&tmp, &aClass::aTest1);
function1(&ClosureSingleton<aClass, void, int, int>::funcPtr);
ClosureSingleton<aClass, int, int, int>::getInstance().setClosure(
&tmp, &aClass::aTest2);
printf(
"function2: %d\n",
function2(&ClosureSingleton<aClass, int, int, int>::funcPtr));
return 0;
}
Of course, this has the obvious downside that the closure needs to be set before every call, as well as some thread safety issues. Not ideal, but potentially workable in specific circumstances
Use something like asmjit or dynamic compilation to dynamically compile and pass the function in to the C code. This will only work on machines that allow heap section to be marked as executable. It is also very much non-portable as you will be writing assembly code to accomplish this. However, if you get it working, you will indeed have a true closure, albeit a substantially higher cost to creating the closure compared to how most programming languages implement closures (they do not duplicate the function assembly, instead they use a context object)
Patch the lib/dll that has the function handler to change it's signature to allow a context object. Again, a very brittle and non optimal solution.
My original answer, which does not really answer the question, but people found it useful:
Not sure why this incredibly simple solution has been passed up:
#include <stdio.h>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d\n", a, b, a + b);
}
};
template<class C>
void function1(void (C::*function)(int, int), C& c)
{
(c.*function)(1, 1);
}
void function1(void (*function)(int, int)) {
function(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d\n", a , b , a - b);
}
int main (int argc, const char* argv[])
{
aClass a;
function1(&test);
function1<aClass>(&aClass::aTest, a);
return 0;
}
Output:
1 - 1 = 0
1 + 1 = 2
I made the member function as static and all works:
#include <iostream>
class aClass
{
public:
static void aTest(int a, int b)
{
printf("%d + %d = %d\n", a, b, a + b);
}
};
void function1(int a,int b,void function(int, int))
{
function(a, b);
}
void test(int a,int b)
{
printf("%d - %d = %d\n", a , b , a - b);
}
int main (int argc, const char* argv[])
{
aClass a;
function1(10,12,test);
function1(10,12,a.aTest); // <-- How should I point to a's aClass::test function?
getchar();return 0;
}
If you actually don't need to use the instance a
(i.e. you can make it static like #mathengineer 's answer)
you can simply pass in a non-capture lambda. (which decay to function pointer)
#include <iostream>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
void function1(void (*function)(int, int))
{
function(1, 1);
}
int main()
{
//note: you don't need the `+`
function1(+[](int a,int b){return aClass{}.aTest(a,b);});
}
Wandbox
note: if aClass is costly to construct or has side effect, this may not be a good way.
You can stop banging your heads now. Here is the wrapper for the member function to support existing functions taking in plain C functions as arguments. thread_local directive is the key here.
http://cpp.sh/9jhk3
// Example program
#include <iostream>
#include <string>
using namespace std;
typedef int FooCooker_ (int);
// Existing function
extern "C" void cook_10_foo (FooCooker_ FooCooker) {
cout << "Cooking 10 Foo ..." << endl;
cout << "FooCooker:" << endl;
FooCooker (10);
}
struct Bar_ {
Bar_ (int Foo = 0) : Foo (Foo) {};
int cook (int Foo) {
cout << "This Bar got " << this->Foo << endl;
if (this->Foo >= Foo) {
this->Foo -= Foo;
cout << Foo << " cooked" << endl;
return Foo;
} else {
cout << "Can't cook " << Foo << endl;
return 0;
}
}
int Foo = 0;
};
// Each Bar_ object and a member function need to define
// their own wrapper with a global thread_local object ptr
// to be called as a plain C function.
thread_local static Bar_* Bar1Ptr = NULL;
static int cook_in_Bar1 (int Foo) {
return Bar1Ptr->cook (Foo);
}
thread_local static Bar_* Bar2Ptr = NULL;
static int cook_in_Bar2 (int Foo) {
return Bar2Ptr->cook (Foo);
}
int main () {
Bar1Ptr = new Bar_ (20);
cook_10_foo (cook_in_Bar1);
Bar2Ptr = new Bar_ (40);
cook_10_foo (cook_in_Bar2);
delete Bar1Ptr;
delete Bar2Ptr;
return 0;
}
Please comment on any issues with this approach.
Other answers fail to call existing plain C functions: http://cpp.sh/8exun

Is there a better way to provide this function to a constructor?

I have a class A which has a constructor with a function argument: i.e.
class A {
public:
A(int (*f)(int);
};
I can create this class and have it use func() with, for example,
int func(int n);
A a(func);
I would like to invoke this class a number of times, but have it use internally func(n)+m instead of func(n). I would prefer not to change class A. I could create a new class to define the function I want
class B {
int (*func)(int n);
int m;
public:
B(int (*ff)(int),int mm) : func(ff),m(mm) {}
int myfunc(int n) { return(func(n)+m);
};
However, I don't think it is possible to convert a pointer to myfunc into a pointer with the required signature for A's constructor.
The way I have chosen is similar to the above, but with myfunc() and associated variables stored in the global space:
int m;
int (*func)(int);
int myfunc(int n) { return(func(n)+m); }
void setupmyfunc(int mm,int (*ff)(int)) { m=mm; func=ff; }
Then I can can create my A object with
setupmyfunc(m,func);
A a(myfunc);
This works, but seems inelegant to me. Is there a better way?
Stateless lambdas are implicitly convertible to function pointers so you can just use that without modifying your class A and without creating another class B. That is if I understood your question correctly.
class A {
public:
A(int (*f)(int)) {};
};
int func(int n) { return n * 10; }
auto test()
{
A a{[](int n) { return func(n) + 1; }};
}
std::function can hold callable objects (functions, function objects, member function pointers (with object to bind to), etc. It uses some type-erasure such that it can have this genericity, but comes at the cost of internal overhead to actually invoke it, often equivalent to a virtual function call.
Here's an example, where A takes a std::function, which allows you to pass in lambdas.
#include <functional>
#include <iostream>
class A {
std::function<int(int)> func_;
public:
A(std::function<int(int)> func) : func_(func) {}
int call(int x) {
return func_(x);
}
};
int foo(int x) {
return x * 123; // whatever
}
int main() {
// here's your wrapper function to do func(x)+m (m==9 in this case)
A obj([](int x) { return foo(x) + 9; });
int result = obj.call(123);
std::cout << result << '\n';
}
https://godbolt.org/z/94MfGM67K
Update:
Given the rejection of both answers so far, using std::function is out because it changes class A, and the obvious use of state-full lambdas for composition and capturing customization data is also out, you will need to get more creative and possibly ugly. If you can't change A, then you can't change the signature of the function passed to a, so making the lambda take its data as another argument is also out.
Seems to me that leaves just one thing: using state that is outside the function (i.e. global data or encoded in a template non-type template parameter) as a form of pseudo-capture that an otherwise stateless function can use. I reject the global approach in general, though there's interesting aspects to it, and only present a template solution:
Now you write your free-standing functions and can compose them with a template:
#include <iostream>
using F = int(*)(int);
class A {
public:
A(F f) : f_(f) { }
int operator()(int x) { return f_(x); } // Added for demo
private:
F f_;
};
template <F FuncF, F FuncG>
int compose(int n) {
return FuncF(FuncG(n));
}
int func(int n) { return n * 1000; }
int add888(int n) { return n + 888; }
int add999(int n) { return n + 999; }
int main() {
A a1(compose<add888, func>);
A a2(compose<add999, func>);
std::cout << a1(1) << " " << a2(1) << " " << a1(1);
}
// output: 1888 1999 1888
https://godbolt.org/z/8KsqbTcTd
This works as far back as c++11, and replacing the "using" with "typedef" it work in C++98.

Is it safe to pass lambda to function that is going out of scope (lambda executes after the method returns)?

I am learning C++ so maybe my question is dumb. I am creating a function that takes a lambda as a parameter. I just want to know if its safe to call it when the lambda function goes out of scope. With code is easier to explain what I mean:
struct SomeStruct
{
// store pointer to callback function
void (*callback)(bool);
int arg1;
int arg2;
};
void some_method(int arg1, int arg2, void (*on_complete_callback)(bool))
{
SomeStruct s;
s.callback = on_complete_callback;
s.arg1 = arg1;
s.arg2 = arg2;
// this helper class will copy the struct even though it is passed by reference
SomeHelperClass->SomeQueue.enqueue( &s );
// do work on a separate task/thread
SomeHelperClass->CreateThread([](){
// get copy of struct
SomeStruct s_copy;
SomeHelperClass->SomeQueue.dequeue( &s_copy );
// do work that takes time to complete
// IS IT SAFE TO CALL THIS CALLBACK FUNCTION?
s_copy.callback(true);
});
}
So my question is given that code if its safe to have something like this?
void method_1()
{
void (*foo)(bool) = [](bool completedCorrectly)
{
cout << "task completed :" << completedCorrectly << endl;
};
some_method(1,2,foo);
// at this point foo should be deleted no?
// why does this work if foo is executed after method_1 completes and its stack is deleted?
// can I have code like that?
}
Edit 2
Here is the same question with working code instead of pseudo code:
#include <iostream> //for using cout
using namespace std; //for using cout
// 3 pointers
int* _X; // points to integer
int* _Y; // points to integer
void (*_F)(int); // points to function
void print_values()
{
cout << "x=" << *_X << " and y=" << *_Y << endl;
}
void some_function()
{
// create variables that live on stack of some_function
int x = 1;
int y = 2;
void (*foo)(int) = [](int someInt)
{
cout << "value passed to lambda is:" << someInt << endl;
};
// point global variables to variables created on this stack x,y and foo
_X = &x;
_Y = &y;
_F = foo;
// works
_F(11);
// works
print_values();
// when exiting variables x,y and foo should be deleted
}
int main(void)
{
// call some function
some_function();
// DOES NOT WORK (makes sense)
print_values();
// WHY DOES THIS WORK? WHY FOO IS NOT DISTROYED LIKE X AND Y?
_F(10);
return 0;
}
If I where to call that method many times and each time with a different lambda will it work? Will the callback method call the correct lambda every time?
A lambda expression is like a class. It is a blueprint for instantiating objects. Classes exist only in source code. A program actually works with objects created from the blueprint defined by a class. Lambda expressions are a source code blueprint for creating closures. Each lambda expression is transformed into a class by the compiler and instantiated into an object called closure. This class has the ability to capture values (that's that the [] part does) and take parameters (that's that the () part does) for its call operator.
Here is an example:
int main()
{
int i = 42;
auto l = [i](int const x){std::cout << x+i << '\n';};
l(2);
}
The compiler transforms this into something similar to the following (generated with https://cppinsights.io/).
int main()
{
int i = 42;
class __lambda_6_11
{
public:
inline /*constexpr */ void operator()(const int x) const
{
std::operator<<(std::cout.operator<<(x + i), '\n');
}
private:
int i;
public:
__lambda_6_11(int & _i)
: i{_i}
{}
};
__lambda_6_11 l = __lambda_6_11{i};
l.operator()(2);
}
You can see here a class that implements the call operator (operator()) with an int argument. You can also see the constructor taking an argument of type int. And then you can see the instantiation of this class at the end of main and the invocation of its call operator.
I hope this helps you understand better how lambdas work.