Why and how does this work?
它的工作原理是因为:
- lambda表达式导致生成一个独特的类在编译时命名。
- 该类的类型由编译器内部命名。
- 因此编译器可能会为
x
想出类似<lambda_30560bd1c97ca682d011cd006c362574>::()::Local
的东西。
你可以得到拉姆达的类型,然后使用该声明包含在它的enum class
类型的对象:
auto lambda = []() {
enum class Local { X = 0, Z = 1 };
return Local::X;
};
int main() {
auto x = lambda(); // No error! Why and what type is auto in this case?
//auto y = Local::X; // Error! Of course!
using x_type = decltype(x);
x_type y;
y = x_type::Z; // can refer to enum members here
y = x;
}
The enum class Local
is not known outside the lambda a type.
真,但enum class
是,如果访问相关的命名空间已解决。所以内部<lambda_30560bd1c97ca682d011cd006c362574>::()::Local
可以在lambda内部解析为Local
,但在编译之前不可能猜到这个名字,但我们可以使用decltype
或auto
来获取类型。
It's a enum class
and therefore cannot be of type int
without a cast
正确。但它的存在方式与enum class
可能存在于常规class
或struct
内部的方式相同。
Without a known type, how can I continue work with that value outside the lambda?
该lambda以外的这种类型的实用程序是有限的。这不是一个int
,而是有其独特的类型,所以即使它可以间接获得也没有多大价值。
您可以使用** may **几次。这只是一个猜测吗? 这是一种类型的删除,因为没有**已知类型**,我怎么能继续使用lambda之外的值?它是否受到处理一个'int'作为基础类型自动?对不起,你的回答并不令人满意。 – cwschmidt
你在使用哪种编译器? '使用x_type = typename decltype(x);'似乎不适用于GCC。 (“主要。CPP:10:29:错误: '之前decltype' 使用x_type预计嵌套名称 - 符=类型名称decltype(X);“) – cwschmidt
@cwschmidt它只是'使用x_type = decltype(X);'无需'类型名称。' –