I came across a naming problem while working with the xlib library:
I'm using a struct which has a member called "class". I assume this library is mostly used in plain C programs. So there's no problem.
But I'm programming in C++ and here the name "class" is a keyword and cannot be used to denote variables. So, if I'm accessing the struct via
myvariable = mystruct->class;
I'm getting the error:
expected unqualified-id before ‘class’
Given that I cannot change the struct itself, how can I access this struct member despite the naming conflict?
Given that I cannot change the struct itself, how can I access this struct member despite the naming conflict?
Maybe you can rename it using a #define, something like
#define class xclass
#include "header.h"
#undef class
// ...
myvariable = mystruct->xclass;
class
is a keyword in C++. You cannot use it as a variable.
If you want to still access it than you can code that part in C and then compile it with c compiler:
typedef struct foo {
bar class;
} foo;
bar *getClassPtr(foo *p) { return &(p->class); }
Include that part in your C++ code using,
extern "C" {
bar *getClassPtr(foo *);
}
bar &getClass(foo &s) { return *getClassPtr(&s); }
You might also want const versions.
You still can't include the struct definition in your C++ code, so you may have to wrap the other members of foo
in the same way. Unless link-time optimization can inline getClassPtr
, there's some overhead in the call, compared with accessing the struct member directly from C++. Normally this will be negligible, but it's worth knowing about.
You may want to find info about extern "C".
You say that you're using XLib. I can only find two places in my Xlib.h
where class
is used as a structure member: Visual
and XWindowAttributes
. In both cases, the offending member is wrapped like this:
#if defined(__cplusplus) || defined(c_plusplus)
int c_class;
#else
int class;
#endif
Similar hackery appears in XColormapEvent
to take care of the new
member.
So you should be fine unless your C++ compiler isn't defining any of the necessary macros; but that would also break the usual extern "C" { ... }
wrappers as well so the problem is most likely elsewhere. If you're using a struct that isn't part of the standard XLib then you should apply the above hack by hand and have a stern discussion with the library's author (and if that's you then angrily talk to yourself for a bit and we'll pretend not to listen).
If you are having trouble with the XLib structs, then try using the C++ version of the member names:
myvariable = mystruct->c_class;
mynew = ev->c_new;
Class is a reserved keyword in C++ and cannot be used as a variable name. You will have to rename the variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With