Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

well, that's a possibility but only works in the simplest case of C-like structs. What if I have this API instead :

    struct MyWidget {
        void setFoos(const std::vector<int>& foos) { m_foos = foos; updateUI(); }
    };
or this :

    struct MyWidget {
        void addFooInstance(int);
    };
Also, ugh. macros. what happens if you talk to 5 different network protocols all with more-or-less-JSON-like semantics - do you now have ARRAY_ITEM_JSON, ARRAY_ITEM_BSON, ARRAY_ITEM_CBOR, ARRAY_ITEM_YAML ? What when the format changes so that `ARRAY_ITEM("foo", foo, INT, 3)` now wants floats ? woohoo, magic truncation instead of a compile error.

As they say : thanks but no thanks, I'll stay with `for (auto& [key, value] : o.items())` which ensures that everyone including the fresh-out-of-school student can understand what happens without needing to read obtuse macro definitions



> What if I have this API instead

I say let data be data and write code where you need code. How does the library handle this in one step? How long does it take you to find out?

> Also, ugh. macros.

Data macros are the best. You don't have to debug them at runtime, they let you get rid of a lot of boilerplate such as compile-time computations (e.g. offsetof(), sizeof())

> do you now have ARRAY_ITEM_JSON, ARRAY_ITEM_BSON, ARRAY_ITEM_CBOR, ARRAY_ITEM_YAML

I'm really sorry if you have to do that. I never had, and likely never will. But I'd probably just write the example I gave, in 5 flavours, in 5 separate implementation files. The alternative, dealing with 5 oversized libraries that approach this thing in a totally different way, is not appealing to me at all.

> What when the format changes so that `ARRAY_ITEM("foo", foo, INT, 3)` now wants floats ? woohoo, magic truncation instead of a compile error.

No, runtime error message about a wrong type in a JSON payload. Or if you mean this: the type of the C array's elements changed from int to float. Then just check the type of the array elements against the specified type (INT) which should expect a specific C type. There are easy ways to get a representation of the array element type in C++ as well as an in C (the macro can do it automatically).

> obtuse macro definitions

#define ARRAY_ITEM(_srcfield, _arraylength, _basetype, _dstfield) { .srcfield=_srcfield, .typekind=TYPE_ARRAY, .arraylength=_arraylength, .basetype=_basetype, .offset=offsetof(MyStruct, _dstfield) }

If you think that is obtuse reconsider C++ templates.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: