如何在 C++11 中将 lambda 表达式存储为类的字段?

How can I store a lambda expression as a field of a class in C++11?(如何在 C++11 中将 lambda 表达式存储为类的字段?)

本文介绍了如何在 C++11 中将 lambda 表达式存储为类的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个类,客户端可以在其中存储 lambda 表达式,例如 []() ->void {} 作为类的一个字段,但我不知道怎么做.一个答案建议使用 decltype,我尝试过但没有成功.这是一个 ideone 源链接.以下是来源和结果:

I'd like to create a class where the client can store a lambda expression like []() -> void {} as a field of the class, but I can't figure out how to do so. One answer suggested using decltype, which I tried with no success. Here is a ideone source link. The below is the source and result:

#include <cstdio>
auto voidLambda = []()->void{};

class MyClass {
public:
     decltype(voidLambda) t;
     MyClass(decltype(voidLambda) t) { 
        this->t = t;
     }
};

int main() {
   MyClass([] {
      printf("hi");
   });
}

结果:

prog.cpp: In constructor 'MyClass::MyClass(<lambda()>)':
prog.cpp:3:79: error: no matching function for call to '<lambda()>::__lambda0()'
prog.cpp:2:20: note: candidates are: <lambda()>::<lambda>(const<lambda()>&)
prog.cpp:2:20: note:                 <lambda()>::<lambda>(<lambda()>&&)
prog.cpp:3:88: error: no match for 'operator=' in '((MyClass*)this)->MyClass::t = t'
prog.cpp: In function 'int main()':
prog.cpp:5:27: error: no matching function for call to 'MyClass::MyClass(main()::<lambda()>)'
prog.cpp:3:48: note: candidates are: MyClass::MyClass(<lambda()>)
prog.cpp:3:14: note:                 MyClass::MyClass(const MyClass&)

有人知道怎么做吗?

推荐答案

如果您希望类成员成为 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 ints 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.
}

希望这有帮助!

这篇关于如何在 C++11 中将 lambda 表达式存储为类的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 C++11 中将 lambda 表达式存储为类的字段?

基础教程推荐