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

标签 c++ visual-studio visual-c++ lambda capture

我有以下代码:

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

相关文章:

c++ - 存储结构的动态数组

c++ - 复制构造函数(深复制)c++

c++ - 在openCV中访问特定图像中所有像素的RGB值

c# - 无法将自定义 ActiveX 控件添加到 .NET Core WinForms 应用程序,但 .NET Framework 应用程序工作正常

c - 使用 _pipe 非 block 重定向 STDOUT

visual-c++ - 比较 TCHAR 和 VC++ 中的字符串值?

c++ - visual studio 2012 中 Eigen 类型 vector 的自动向量化表现不佳

ios - 如何在 Visual Studio for Mac 上更改 iOS 模拟器

c++ - 访问线程内的主对话框变量 (MFC)

.net - 如何设置相对于项目文件的资源文件路径?