首页 > 解决方案 > 如何在 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 中编译此代码。

标签: c++visual-studiovisual-c++lambdacapture

解决方案


这似乎是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 中。


推荐阅读