我有以下代码:
#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的错误;在lambda中确定this
指针的类型时:
For the purpose of name lookup, determining the type and value of the this pointer and for accessing non-static class members, the body of the closure type's function call operator is considered in the context of the lambda-expression.
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
的类型应在lambda中为Bobo*
。
关于c++ - 如何在lambda中访问捕获的此指针的 `typeid`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62431391/