Search code examples
c++functionstructparametersanonymous-struct

Define an anonymous struct in function call


I can already do this:

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);

I would like to know if it is possible to move the struct definition right inside the function call, so that I could for example define a macro like this one:

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

When I try this I get 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;
    }
});

Solution

  • Your requirements can be satisfied with a stateful, mutable lambda:

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