更新时间:2022-02-22 22:41:13
如果您希望类成员成为 lambda 表达式,请考虑使用 std::function<>
包装器类型(来自
标头),它可以保存任何可调用的函数.例如:
If you want a class member to be a lambda expression, consider using the std::function<>
wrapper type (from the <functional>
header), which can hold any callable function. For example:
std::function<int()> myFunction = []() { return 0; }
myFunction(); // Returns 0;
这样,您就不需要知道 lambda 表达式的类型.您可以只存储适当函数类型的 std::function
,模板系统将为您处理所有类型.更一般地说,任何具有适当签名的可调用实体都可以分配给 std::function<>
,即使该函子的实际类型是匿名的(在 lambdas 的情况下)或真的复杂.
This way, you don't need to know the type of the lambda expression. You can just store a std::function<>
of the appropriate function type, and the template system will handle all the types for you. More generally, any callable entity of the appropriate signature can be assigned to a std::function<>
, even if the the actual type of that functor is anonymous (in the case of lambdas) or really complicated.
std::function
模板里面的类型应该是你想要存储的函数对应的函数类型.因此,例如,要存储一个接受两个 int
并返回 void 的函数,您需要创建一个 std::function
.对于不带参数并返回 int
的函数,您可以使用 std::function
.在你的情况下,因为你想要一个不带参数并返回 void
的函数,你需要这样的东西:
The type inside of the std::function
template should be the function type corresponding to the function you'd like to store. So, for example, to store a function that takes in two int
s and returns void, you'd make a std::function<void (int, int)>
. For a function that takes no parameters and returns an int
, you'd use std::function<int()>
. In your case, since you want a function that takes no parameters and returns void
, you'd want something like this:
class MyClass {
public:
std::function<void()> function;
MyClass(std::function<void()> f) : function(f) {
// Handled in initializer list
}
};
int main() {
MyClass([] {
printf("hi")
}) mc; // Should be just fine.
}
希望这有帮助!