I'd like to be able to bind a function with set parameters within itself - I've been given an implementation of scheduled callbacks wherein there's a multimap
from std::chrono
time signatures to std::function<void(void)>
, and I want to have this method do some stuff and then schedule to call itself again in the future. Thus, creating a std::bind
of itself to ultimately get into this multimap
with an associated time.
I'm having a devil of a time actually trying to get the syntax right here, and I'm not really able to parse the error messages / see why things aren't working. For example,
#include <functional>
#include <iostream>
class x {
public:
void testBind(char y);
};
void x::testBind(char y) {
std::cout<<"Blah! " << y << "\n";
auto boundItself = std::bind(&x::testBind, &x, std::placeholders::_1);
boundItself('h');
}
produces the following error on the line with std::bind
:
error C2275: 'x': expected an expression instead of a type
https://godbolt.org/z/rncfchvPb
As a toy example, I should be able to get recursive printouts of Blah etc., but the syntax around Bind aren't being cooperative.
https://en.cppreference.com/w/cpp/utility/functional/bind
From the std::bind
documentation, here's an example that DOES work:
struct Foo {
void print_sum(int n1, int n2)
{
std::cout << n1+n2 << '\n';
}
int data = 10;
};
int main()
{
using namespace std::placeholders;
Foo foo;
auto f3 = std::bind(&Foo::print_sum, &foo, 95, _1);
f3(5);
return 0;
}
Now, I notice that in this example, there's first &Foo:print_sum
, e.g. capital F, e.g. the class definition, while the second argument is &foo
, a lowercase, e.g. a specific instance of the class. But how do I get this argument into my bind definition? Do I need to declare a static global instance of my class to use as a sort of placeholder here?