c++ - 如何在 lambda 中访问捕获的 this 指针的“typeid”?
问题描述
我有以下代码:
#include <iostream>
class Bobo
{public:
int member;
void function()
{
auto lambda = [this]() { std::cout << member << '\n'; };
auto lambda2 = [this]() { std::cout << typeid(*this).name() << '\n'; };
lambda();
lambda2();
}
};
int main()
{
Bobo bobo;
bobo.function();
}
行 std::cout << typeid(*this).name(); 在 lambda2() 中可以理解地打印出:
class <lambda_49422032c40f80b55ca1d0ebc98f567f>
但是,如何访问已捕获的“this”指针,以便 typeid 运算符可以返回类型类 Bobo?
编辑:我得到的结果是在 Visual Studio Community 2019 中编译此代码。
解决方案
这似乎是VS的错误;在确定lambdathis
中的指针类型时:
出于名称查找、确定 this 指针的类型和值以及访问非静态类成员的目的,闭包类型的函数调用运算符的主体在 lambda 表达式的上下文中被考虑。
struct X { int x, y; int operator()(int); void f() { // the context of the following lambda is the member function X::f [=]()->int { return operator()(this->x + y); // X::operator()(this->x + (*this).y) // this has type X* }; } };
所以类型this
应该Bobo*
在 lambda 中。
推荐阅读
- visual-studio - 抑制单个编译器错误(例如 NU1603)
- php - 使用 PHP 项目关键字解析 XML
- c# - ModelBinder 的文化默认行为问题
- format - matlab coder - 在创建的 C 代码中更改格式
- python - Python 正则表达式中的 Re.search 无法按预期工作
- r - 用户定义的函数在 R 中没有响应
- apache - Apache 使用的 LDAP 过滤器始终不返回任何条目
- c# - char 数组返回值,如 50'w'
- mysql - MySQL - 从 2 个表中选择,其中结果中的几列应基于条件语句
- java - 如何绕过 BiConsumer lambda 函数中的“对象无法转换”?