gpt4 book ai didi

c++ - 如何在lambda中访问捕获的此指针的 `typeid`?

转载 作者:行者123 更新时间:2023-12-01 14:52:17 27 4
gpt4 key购买 nike

我有以下代码:

#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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com