Reputation: 3189
I'm essentially trying to have it so I can create a generic callback from any lamba with captures: GenericCallback([=]{});
Using the following class:
template<typename T> class GenericCallback : public Callback {
public:
GenericCallback(const std::function<T>& f) {
mFunction = f;
}
void Call() override {
mFunction();
}
std::function<T> mFunction;
};
The problem is it expects me to define the template arguments. There's no issues doing so in general, but if I use any captures, whether it's using [=]
or specific arguments, the type becomes impossible for me to shove it into this structure.
My end goal is to simply call these functions at a later time with a specified condition.
A case where this errors:
int v = 5;
GenericCallback<void()>([=]{ int x = v; });
Upvotes: 0
Views: 69
Reputation: 44268
You misunderstand the whole concept of std::function<>
and overcomplicated the issue. You can use std::function<void()>
in this case and bind pretty match anything to it, you need to change type in <>
only when you need to change calling signature. So
class Callback {
public:
using callback_type = std::function<void()>;
Callback( callback_type cb ) : m_cb( cb ) {}
void call() { m_cb(); }
private:
callback_type m_cb;
};
int main()
{
int v;
Callback c( [=]{ int x = v; } );
c.call();
}
would simple work and you do not need template there. You need to change type in std::function
in this case only if you want Callback::call()
to pass something to that callback or make it to return something and I doubt you plan to do that.
Upvotes: 1