我有一个类,我想在编译时对其执行操作。在下面的示例中,我有一个IntWrapper带有重载的简单结构operator+。在任何正常上下文中使用此类似乎都可以正常工作,但在 lambda 内部使用时会失败,为什么?
struct IntWrapper
{
consteval IntWrapper operator+(const IntWrapper& other) const
{
return { x + other.x };
}
int x;
};
int main()
{
// Adding normally works just fine
constexpr IntWrapper c1 = IntWrapper{ 1 } + IntWrapper{ 1 };
auto adder = [](IntWrapper x) { return x + x; };
// Using a lambda to add doesn't work
constexpr IntWrapper c2 = adder(IntWrapper{ 1 });
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能让这个对象在编译时在 lambda 上下文中工作?