mercredi 8 janvier 2020

How can I test that a macro is being used in global/namespace scope?

I'd like to write a header that lets me declare preferences with a syntax similar to:

declpref("some.pref.name", "description");

Which registers some.pref.name with the given description which some global registry so I can easily introspect what preferences my code has declared, set their values from various sources, etc.

I'd probably do this with some sort of static-construction before main magic:

#define declpref(name, desc)                       \
    {                                              \
        static struct __pref {                     \
            __pref() {                             \
                register_preference(name, desc);   \
            }                                      \
        } __static_pref;                           \
    }

The problem being that the above code wouldn't work the way I want it to if used in a local scope:

void some_function() {
    declpref("some.pref", "description"); // won't register until some_function called
} 

I think that I'm OK with forcing preference declarations to be done at global/namespace scope since they're supposed to be a globally unique name anyways.

How can I check the scope that its being declared in and throw an error though?

Aucun commentaire:

Enregistrer un commentaire