假设您有一个场景,当您想要创建一个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
and rhs
不是常量表达式。有没有办法可以通过this
and rhs
给当地人constexpr
lambda?
You can't capture the a
members of this
and rhs
(by reference) and maintain constexpr
validity1; however, you can pass those members as by (const) reference arguments to your 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 Or maybe you can, but it's messy: Lambda capture as const reference? https://stackoverflow.com/q/3772867/10871073
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)