小编Mat*_*uir的帖子

在 C++ 编译时在 lambda 中的自定义类型上使用运算符

我有一个类,我想在编译时对其执行操作。在下面的示例中,我有一个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 上下文中工作?

c++ lambda constexpr

1
推荐指数
1
解决办法
48
查看次数

标签 统计

c++ ×1

constexpr ×1

lambda ×1