[英]Deducing lambdas to std::function<T>
I'm essentially trying to have it so I can create a generic callback from any lamba with captures: GenericCallback([=]{});
我实质上是想拥有它,因此我可以从任何带有捕获功能的lamba创建一个通用回调:
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; });
You misunderstand the whole concept of std::function<>
and overcomplicated the issue. 您误解了
std::function<>
的整个概念,并使问题变得更加复杂。 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. 在这种情况下,您可以使用
std::function<void()>
并将任何内容完全匹配,只有在需要更改调用签名时才需要在<>
更改类型。 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. 在这种情况下,仅当您希望
Callback::call()
将某些内容传递给该回调或使其返回某些内容时,才需要更改std::function
类型,而我怀疑您打算这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.