在编译时将此指针和 class 方法的参数传递给本地 lambda 函数
Passing this pointer and arguments of class method to local lambda function at compile time
假设您有一个场景,当您想要在一个方法中创建一个 constexpr
lambda 以在编译时计算某些东西。
struct A {
int a;
constexpr A(int a) : a(a) {}
constexpr auto operator+(const A& rhs) {
constexpr auto l = [&]() {
return A(this->a + rhs.a);
};
return l();
}
};
此代码无法编译,因为编译器认为 this
和 rhs
不是常量表达式。有没有办法将 this
和 rhs
传递给本地 constexpr
lambda?
您不能 捕获 this
和 rhs
的 a
成员(通过引用)并维护 constexpr
有效性1;但是,您 可以 将这些成员作为 by (const) reference 参数传递给您的 lambda:
struct A {
int a;
constexpr A(int a) : a(a) { }
constexpr auto operator+(const A rhs) {
constexpr auto l = [](const int& ta, const int& ra) {
return A(ta + ra);
};
return l(a, rhs.a); // Or return l(this->a, rhs.a) if you prefer
}
};
1 或 也许可以,但它很乱:Lambda capture as const reference?
假设您有一个场景,当您想要在一个方法中创建一个 constexpr
lambda 以在编译时计算某些东西。
struct A {
int a;
constexpr A(int a) : a(a) {}
constexpr auto operator+(const A& rhs) {
constexpr auto l = [&]() {
return A(this->a + rhs.a);
};
return l();
}
};
此代码无法编译,因为编译器认为 this
和 rhs
不是常量表达式。有没有办法将 this
和 rhs
传递给本地 constexpr
lambda?
您不能 捕获 this
和 rhs
的 a
成员(通过引用)并维护 constexpr
有效性1;但是,您 可以 将这些成员作为 by (const) reference 参数传递给您的 lambda:
struct A {
int a;
constexpr A(int a) : a(a) { }
constexpr auto operator+(const A rhs) {
constexpr auto l = [](const int& ta, const int& ra) {
return A(ta + ra);
};
return l(a, rhs.a); // Or return l(this->a, rhs.a) if you prefer
}
};
1 或 也许可以,但它很乱:Lambda capture as const reference?