在函数调用中定义匿名结构

时间:2018-11-30 09:14:01

标签: c++ function struct parameters anonymous-struct

我已经可以这样做:

struct {
    uint64 _i;
    bool operator()(uint64 elem)
    {
        const uint64 i = _i++; return elem & i; // Just an example
    }
} filter;

// Templated function
Array<uint64> clone = Containers::filter(array, filter);

我想知道是否可以在函数调用内部移动结构定义,以便例如可以定义一个这样的宏:

Array<uint64> clone = Containers::filter(array, ENUMERATE(i, elem, elem & i)); // Same as above

尝试此操作时,我会得到expected primary-expression before 'struct'

Array<uint64> clone = Containers::filter(array, struct {
    uint64 _i;
    bool operator()(uint64 elem)
    {
        const uint64 i = _i++; return elem & i;
    }
});

1 个答案:

答案 0 :(得分:3)

您可以使用有状态的可变lambda来满足您的要求:

Array<uint64> clone = Containers::filter(
    array,
    [_i = uint64{0}](uint64 elem) mutable -> bool {
        const uint64 i = _i++;
        return elem & i;
    }
);