C++ Recursion Stack Frame Identifier - c++

Take an example:
int foo(){
if(<THIS IS THE SECOND TIME YOU CALL FOO>) // I need some indicator like this
return 1;
else
return foo();
}
Essentially, I'm looking for an indicator that tells me "hey this is the second time that you have called foo". (I'm trying to avoid using static variables or changing foo function itself, just for sake of this exercise.)
I'm guessing if there's any variable related to the function's current stack frame (or maybe the caller stack frame) which I can exploit and use?

You can leverage a thread_local counter, along with a RAII object to increment a counter at some point in your function and decrement it when the thread leaves the function.
By creating an instance of this object with automatic storage duration (as a local variable) near the top of the function you can know how many times the current thread has called the function without returning yet.
By including an auto template argument, you can also provide the function as the template argument to allow the class to be reused in different functions.
Live example :
template<auto>
class stack_count
{
public:
stack_count() {
counter()++;
}
~stack_count() {
counter()--;
}
stack_count(const stack_count&) = delete;
void operator=(const stack_count&) = delete;
int get() const {
return counter();
}
private:
static int & counter() {
thread_local int counter = 0;
return counter;
}
};
#include <iostream>
int foo()
{
stack_count<&foo> counter;
std::cout << counter.get() << '\n';
if(counter.get() == 2) {
return 42;
}
else {
return foo();
}
}
int main()
{
const auto result = foo();
std::cout << "foo() : " << result << '\n';
}

I'm assuming you want to detect when foo has been called recursively, not when it's been called twice.
And I am guessing you're trying to avoid changing the function signature of foo, but can do whatever you want with the implementation. If that's the case, an inner "implementation" (impl) function that lets you pass the recursion count. The original function foo just calls the implementation function with a seed value:
int fooImpl(int count) {
if (count == 2) {
// this is the second time you've called foo
return 0; // return any value you want
} else {
return fooImpl(count+1);
}
}
int foo(){
return fooImpl(1);
}
And if you don't want to escape the bounds of the function, then use an internal lambda:
int foo() {
std::function<int(int)> fn;
fn = [&fn](int count)->int {
if (count == 2) {
// this is the second time you've called foo
return 0; // return any value you want
}
else {
return fn(count + 1);
}
};
return fn(1);
}

Related

How can I call a function from an array of functions via its index?

A beginner's question I couldn't find answered online, likely because I don't know the terminology.
I want to call one of a list of procedures based on a computed index value. That is, given a '1', invoke firstProc(), '2' invokes secondProc() and so on.
All the procedures are void functions with no arguments.
I can implement that with switch/case, but what I'd prefer is something like:
void* action[2] {*firstProc, *secondProc};
(This compiles, but warns: invalid conversion from 'void (*)()' to 'void*')
and then later:
action[get_index()]();
The compiler objects that 'action' can't be used as a function.
This must be possible, right? I've tried several variations but I can't get past the use of the selected ('action[index]') as a function.
There are two equivalent ways to do what you want. The explanation is given as comments in the code snippets.
Method 1
#include <iostream>
void foo()
{
std::cout << "Hello";
}
void foo2()
{
std::cout << " wolrd!";
}
int main()
{
void (*a)() = foo;// a is a pointer to a function that takes no parameter and also does not return anything
void (*b)() = foo2;// b is a pointer to a function that takes no parameter and also does not return anything
//create array(of size 2) that can hold pointers to functions that does not return anything and also does not take any parameter
void (*arr[2])() = { a, b};
arr[0](); // calls foo
arr[1](); //calls foo1
return 0;
}
Method 1 can be executed here.
In method 1 above void (*a)() = foo; means that a is a pointer to a function that takes no parameter and also does not return anything.
Similarly, void (*b)() = foo2; means that b is a pointer to a function that takes no parameter and also does not return anything.
Next, void (*arr[2])() = { a, b}; means that arr is an array(of size 2) that can hold pointers to functions that does not return anything and also does not take any parameter.
Method 2
#include <iostream>
void foo()
{
std::cout << "Hello";
}
void foo2()
{
std::cout << " wolrd!";
}
int main()
{
//create array(of size 2) that can hold pointers to functions that does not return anything
void (*arr[2])() = { foo, foo2};
arr[0](); // calls foo
arr[1](); //calls foo1
return 0;
}
Method 2 can be executed here.
You need the correct syntax for your function pointer array. void(*func_ptr[])().
Example:
void func1() { std::cout << "Hallo" << std::endl; }
void func2() { std::cout << "World" << std::endl; }
// if you need a different signature for your functions like:
int func3(int n) { std::cout << "n1 " << n << std::endl; return n*2; }
int func4(int n) { std::cout << "n2 " << n << std::endl; return n*3; }
int main()
{
// array of function pointer which
// have no parameter and void as return value
void(*func_ptr[])()={ func1, func2 };
for ( unsigned int idx = 0; idx<2; idx++ )
{
func_ptr[idx]();
}
// array of function pointers with int return value and int as
// parameter
int(*func_ptr2[])(int)={ func3, func4 };
for ( unsigned int idx = 0; idx<2; idx++ )
{
std::cout << "retval: " << func_ptr2[idx](6) << std::endl;
}
}
I've stopped using function pointers (though they still can be useful).
I usually use std::function (and lambdas) when working with functions
Code for arrays of functions then look like this.
I used std::vector but std::array for fixed size should work fine too.
#include <vector>
#include <functional>
#include <iostream>
void some_function()
{
std::cout << "some function\n";
}
int main()
{
// std::function, abstraction of a function, function signature = template parameter, so void () is function returning a void, no parameters
// std::vector, runtime resizable array
// constructor : 4 time a lambda function printing out hello world.
std::vector<std::function<void()>> functions(4, [] { std::cout << "Hello World!\n"; } );
// easy syntax to assign an existing function to an index
functions[1] = some_function;
// replace a function in the vector with another one (lambda)
functions[2] = [] { std::cout << "booh\n"; };
// call function at index 0
functions[0]();
std::cout << "\n\n";
// or loop over all the functions and call them (classic for loop)
for (std::size_t n = 0; n < functions.size(); ++n) functions[n]();
std::cout << "\n\n";
// or loop over all the functions (range based for loop)
for (const auto& function : functions) function();
return 0;
}

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.

Accessing the contents of a function from a struct defined inside that function

typedef void (*voidfunc)();
void somefunc(voidfunc function)
{
voidfunc func = function;
struct wrapper
{
function(); //does not work
func(); //does not work
};
}
Is there any way at all to access function from inside the struct wrapper? I am trying to see if it is possible to implement python style wrapper. Something like a timer. Where somefunc takes a function, wrapper runs that function and timers it.
Something like this ?
wrapper_struct_type timer(voidfunc function)
{
struct wrapper
{
void timeit()
{
//start time
function(); //does not work
//endtime
//time = end- start
}
};
//return wrapper
}
Working example in python
import time
def timer(func):
def wrapper():
start = time.time()
func()
end = time.time()
print(end - start)
return wrapper
#timer
def somefunc():
print("hello world")
somefunc()
Lambda Solution
You can achieve this using C++ lambdas.
Note my example requires C++14 (or greater) to compile.
#include <iostream>
typedef void (*voidfunc)();
void doNothing() {}
auto foo(voidfunc function)
{
auto wrapper = [function]()
{
int x = 1;
function();
int y = 1;
std::cout << y - x << "\n";
};
return wrapper;
}
int main()
{
auto fn = foo(doNothing);
fn();
foo(doNothing)();
return 0;
}
In the foo function, the function passed to foo is "captured" for use in the lambda's body. Then, the function is executed in the body of the lambda. At the end of the body of foo, the lambda is returned.
Then the main function demonstrates how the foo function can be used. A voidfunc can be passed to foo, and then the returned lambda can be assigned to a variable (in my example it is assigned to fn). Then the returned lambda can be invoked (in my example it is invoked with fn()). Or, the returned lambda can be invoked directly, without using a variable (in my example I do this with foo(doNothing)();).
I use int x and int y as examples since I do not know what precision you might be looking for for time deltas.
Lambda-free Solution
Here is an alternate (and, in my opinion, less elegant) solution that works if lambdas are not supported for the C++ compiler/standard you are compiling with:
#include <iostream>
typedef void (*voidfunc)();
struct Foo
{
voidfunc function;
Foo(voidfunc fn) : function(fn) {}
void wrapper()
{
int x = 1;
function();
int y = 1;
std::cout << y - x << "\n";
}
};
void doNothing() {}
int main()
{
Foo foo(doNothing);
foo.wrapper();
return 0;
}
Here, there is a Foo struct that is passed a voidfunc function via its constructor. The voidfunc is then stored as the function member of the Foo struct (function could be declared as private if desired).
In main in my example, a Foo is created as foo. Then, whenever the wrapper function is executed on foo, the function stored in foo will be executed.
You could create a struct and overload the call operator. The struct will take a std::function<void()> in its constructor. Then simply call the instance of the struct.
std::function gives you type erasure. So as long you have any callable that has the right signature, it will provide a wrapper around it.
#include <iostream>
#include <functional>
#include <chrono>
struct timerit
{
timerit(std::function<void()> fn) : mFunction{fn} {}
void operator()() const
{
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
mFunction();
std::chrono::high_resolution_clock::time_point end = std::chrono::high_resolution_clock::now();
auto dur = end - start;
auto milli = std::chrono::duration_cast<std::chrono::milliseconds>(dur);
std::cout << milli.count() << "ms" << std::endl;
}
std::function<void()> mFunction;
};
void count()
{
for(int i=0; i<1000000; ++i);
}
int main()
{
auto lambda = []() { for(int i=0; i<1000000; ++i); };
timerit t1{lambda}; //lambda
t1();
timerit t2{count}; //function
t2();
return 0;
}
Live demo
Note that you also do this:
timerit{lambda}();
which will invoke the call operator immediately without giving you an variable of type timerit.
You can provide your own implementation inside the call operator and call the function object that you pass in. My implementation sticks closely to the timer example that you provided in your question.

Is it possible to use member function call as default argument?

Here is my code:
struct S
{
int f() { return 1; }
int g(int arg = f()) { return arg; }
};
int main()
{
S s;
return s.g();
}
This fails to compile with the error:
error: cannot call member function 'int S::f()' without object
Trying this->f() doesn't work either, as this may not be used in that context.
Is there a way to make this work, still using the default argument?
Of course it can be worked around by not using default arguments at all:
int g(int arg) { return arg; }
int g() { return g(f()); }
however that gets verbose considering that in the "real code" there are more parameters before arg, and several functions following this pattern. (And even more ugly if there were multiple default arguments in the one function).
NB. This question looks similar at first, but in fact he is asking how to form a closure, which is a different problem (and the linked solution doesn't apply to my situation).
You can only use members there if they are static. From a C++11 draft standard (n3299), §8.3.6/9:
Similarly, a non-static member shall not be used in a default argument, even if it is not evaluated, unless it appears as the id-expression of a class member access expression (5.2.5) or unless it is
used to form a pointer to member (5.3.1).
E.g., this works:
struct S {
static int f() { return 1; }
int g(int arg = f()) { return arg; }
};
int main()
{
S s;
return s.g();
}
This also works (I think that's what the first expression means):
struct S {
int f() { return 42; }
int g(int arg);
};
static S global;
int S::g(int arg = global.f()) { return arg; }
int main()
{
S s;
return s.g();
}
As for this, it is indeed not allowed (§8.3.6/8):
The keyword this shall not be used in a default argument of a member function.
The default arguments page on cppreference.com has a lot of details regarding the subject—it can get quite complex.
If you are allowed to use experimental features from C++17, you can use std::optional from the STL (see here for further details).
In other terms something like:
int g(std::optional<int> oarg = std::optional<int>{}) {
int arg = oarg ? *oarg : f();
// go further
}
EDIT
As suggested in the comments, the code above should be logically equivalent to the one below:
int g(std::optional<int> oarg = std::optional<int>{}) {
int arg = oarg.value_or(f());
// go further
}
This one is a bit more readable (isn't it?), but please note that it executes f in any case.
If that function is expensive, maybe it doesn't worth it.
I add another answer, that is completely different from the previous one and could solve your issue.
The idea is to use another class and the right mix of explicit and non-explicit constructors.
It follows a minimal, working example:
#include <functional>
#include <iostream>
template<class C, int(C::*M)()>
struct Arg {
std::function<int(C*)> fn;
Arg(int i): fn{[i](C*){ return i; }} { }
explicit Arg(): fn{[](C* c){ return (c->*M)(); }} { }
};
struct S {
int f() { return 1; }
int h() { return 2; }
void g(int arg0,
Arg<S, &S::f> arg1 = Arg<S, &S::f>{},
Arg<S, &S::h> arg2 = Arg<S, &S::h>{})
{
std::cout << "arguments" << std::endl;
std::cout << "arg0: " << arg0 << std::endl;
std::cout << "arg1: " << arg1.fn(this) << std::endl;
std::cout << "arg2: " << arg2.fn(this) << std::endl;
}
};
int main() {
S s{};
s.g(42, 41, 40);
s.g(0);
}
The example shows how you can mix both default parameters and non defaulted ones.
It's quite simple to modify it and let g be a function having an empty argument list, as in the original question.
I'm also quite sure that one can refine the example and end with something better than that, anyway it should be a good point from which to start.
It follows the solution applied to the original example from the question:
#include <functional>
template<class C, int(C::*M)()>
struct Arg {
std::function<int(C*)> fn;
Arg(int i): fn{[i](C*){ return i; }} { }
explicit Arg(): fn{[](C* c){ return (c->*M)(); }} { }
};
struct S {
int f() { return 1; }
int g(Arg<S, &S::f> arg = Arg<S, &S::f>{}) {
return arg.fn(this);
}
};
int main() {
S s{};
return s.g();
}
And that's all, it's possible to do that, even without static methods or global variables.
Of course, we can use our this somehow. It's a matter of bending the language a bit...

using function object though function pointer is required

I have to use some legacy code expecting a function pointer, let's say:
void LEGACY_CODE(int(*)(int))
{
//...
}
However the functionality I have is within a functor:
struct X
{
Y member;
X(Y y) : member(y)
{}
int operator()(int)
{
//...
}
};
How should I modify/wrap class X so that LEGACY_CODE can access the functionality within X::operator()(int) ?
Your question makes no sense. Whose operator do you want to call?
X a, b, c;
LEGACY_CODE(???); // what -- a(), b(), or c()?
So, in short, you cannot. The member function X::operator() is not a property of the class alone, but rather it is tied to an object instance of type X.
Search this site for "member function" and "callback" to get an idea of the spectrum of possible approaches for related problems.
The crudest, and quite possibly not-safe-for-use, workaround to providing a free function would go like this:
X * current_X; // ugh, a global
int dispatch(int n) { current_X->operator()(n); }
int main()
{
X a;
current_X = &a;
LEGACY_CODE(dispatch);
}
You can see where this is going...
A simple wrapper function looks like:
int wrapperfunction(int i) {
Functor f(params);
return f(i);
}
If you want to be able to pass the parameters to the functor itself, the simplest way is to sneak them in using (brr) a global variable:
Functor functorForWrapperfunction;
int wrapperfunction(int i) {
functorForWrapperfunction(i);
}
// ...
void clientCode() {
functorForWrapperfunction = Functor(a,b,c);
legacyCode(wrapperfunction);
}
You can wrap it with a class with a static method and a static member if you want.
Here's one compile-time solution. Depending on what you need, this might be a too limited solution for you.
template<typename Func, int Param>
int wrapper(int i)
{
static Func f(Param);
return f(i);
}
A thread-safe version under the restriction that the legacy code is not called with different parameters in a thread.
IMHO, one cannot get rid of global storage.
#include <boost/thread.hpp>
#include <boost/thread/tss.hpp>
class AA
{
public:
AA (int i) : i_(i) {}
void operator()(int j) const {
static boost::mutex m; // do not garble output
boost::mutex::scoped_lock lock(m);
std::cout << " got " << j << " on thread " << i_ << std::endl;
Sleep(200); }
int i_;
};
// LEGACY
void legacy_code(void (*f)(int), int i) { (*f)(i); }
// needs some global storage through
boost::thread_specific_ptr<AA> global_ptr;
void func_of_thread(int j)
{
AA *a = global_ptr.get();
a->operator()(j);
}
void worker(int i)
{
global_ptr.reset(new AA(i));
for (int j=0; j<10; j++)
legacy_code(func_of_thread,j);
}
int main()
{
boost::thread worker1(worker,1) , worker2(worker,2);
worker1.join(); worker2.join();
return 0;
}