我有以下代码:
#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的bug; 在lambda中确定this指针的类型和值时:
为了查找名称,确定this指针的类型和值以及访问非静态类成员,闭包类型的函数调用运算符的主体在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
的类型应该是BOBO*
。
正如@songyuanyao所建议的那样,您的could应该可以工作并产生合适的typeid,所以这可能是一个bug。 但是-这里有一个解决办法:
#include <iostream>
class Bobo
{public:
int member;
void function() {
auto lambda = [this]() { std::cout << member << '\n'; };
auto lambda2 = [my_bobo = this]() {
std::cout << typeid(std::decay_t<decltype(*my_bobo)>).name() << '\n';
};
lambda();
lambda2();
}
};
int main() {
Bobo bobo;
bobo.function();
}
请注意,您可以将typeId(...).name()
替换为正确的类型名(在编译时!) 根据这个答案:
std::cout << type_name<std::decay_t<decltype(*my_bobo)>>() << '\n';