79154378

Date: 2024-11-04 06:24:06
Score: 1
Natty:
Report link

In C, nested types are accessible as if they were declared in the global scope.

In C++, nested types require explicit qualification with the enclosing type (like foo::bar) because they are considered scoped within the enclosing type.

Is it possible to make it compile when included into C++ code without making the struct type declaration unnested?

Yes, try to use #ifdef __cplusplus to make the code compatible with both C and C++ without changing and also use a macro to handle the scoping.

#include <stdio.h>

#ifdef __cplusplus
#define NESTED_STRUCT(foo, bar) foo::bar
#else
#define NESTED_STRUCT(foo, bar) bar
#endif

struct foo {
    struct bar {
        int baz;
    } bar;
};

int main() {
    struct NESTED_STRUCT(foo, bar) a;
    a.baz = 2;
    printf("%d\n", a.baz);
    return 0;
}
Reasons:
  • Blacklisted phrase (1): Is it possible to
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (0.5):
Posted by: Shelton Liu