使用[]和[this]时lambda类型的差异 [英] Difference in type of lambda when using [] and [this]

查看:47
本文介绍了使用[]和[this]时lambda类型的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个db_interface类.并定义了一个lambda类型:

I have a class db_interface. And defined a lambda type:

typedef void (*db_interface_lambda)();

当我以以下方式在类中创建lambda时:[](){ /* do something */ },它具有良好的类型(db_interface_lambda),但是当我使用[this](){ /* do something */ }时,编译器开始对我大喊大叫.

When I create lambda in class in such way: [](){ /* do something */ }, it has good type (db_interface_lambda), but when I use [this](){ /* do something */ }, the compiler starts to shout at me.

cannot convert ‘db_interface::db_interface(std::ifstream&)::<lambda()>’ to ‘std::map<std::basic_string<char>, void (*)()>::mapped_type {aka void (*)()}’ in assignment

如何解决该问题?什么是正确的类型?

How to solve that problem? What is the correct type?

推荐答案

因为lambda仅可隐式地转换为函数指针,当且仅当不捕获任何东西时.

Because lambdas are only implicitly convertible to function pointers if and only if they do not capture anything.

§5.1.2 [expr.prim.lambda] p6

没有 lambda-capture ([]为空)的 lambda-expression 的闭包类型具有一个公共的非虚拟非显式const转换函数,用于具有与闭包类型的函数调用运算符相同的参数和返回类型的函数的指针.

The closure type for a lambda-expression with no lambda-capture ([] is empty) has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator.

顺便说一句,您在typedef那里有一个函数指针,而不是lambda类型. Lambda表达式具有唯一的,未命名的,ununion类类型.您无法命名.

Btw, what you typedef'd there is a function pointer, not a lambda type. Lambda expressions have a unique, unnamed, nonunion class type. You can not name them.

§5.1.2 [expr.prim.lambda] p3

lambda-expression 的类型(也是闭包对象的类型)是唯一的,未命名的ununion类类型

The type of the lambda-expression (which is also the type of the closure object) is a unique, unnamed nonunion class type

这篇关于使用[]和[this]时lambda类型的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆