问题
I have some code that has optional built in code that attempts to detect C++0X. Lets pretend that that works (discussing how bad and how not cross platform that is is out of scope for this question). Lets say it has a #define DETECTCXX0X. iff it is C++0X.
How awful of an idea is it to do this:
#ifndef DETECTCXX0X
#define override
#endif
And do you have any alternatives?
(I suppose the correct thing to do is to just not use explicit overriding).
回答1:
As Igor Tandetnik points out it's legal in C++11 and C++98 to say:
int override = 10;
Because override is not really a keyword even in C++11. If your code does this then your macro will mangle it in C++98 mode. If you prohibit using such identifiers and then your method will work fine. The only problem being that you may forget that rule and get hard to understand error messages. If you're using some kind of linter that you can customize then you can add a rule that eliminates this problem.
Another option is Praetorian's solution:
#ifndef DETECTCXX0X
#define OVERRIDE
#else
#define OVERRIDE override
#endif
This, however, makes for ugly and difficult to read code, IMO.
If you have the luxury to do the following then this is what I recommend:
#ifndef DETECTCXX0X
#error C++11 support required
#endif
If you can't avoid non-C++11 compilers then a second best option, if you have that linter, is to use it with #define override. Third best would be to not use this particular C++11 feature at all. In my view the least desirable option is #define OVERRIDE override.
回答2:
I'd do it slightly differently
#ifndef DETECTCXX0X
#define OVERRIDE
#else
#define OVERRIDE override
#endif
And then define the function as
void foo() OVERRIDE;
Doing so avoids flouting the rules. From §17.6.4.3.1/2 [macro.names]
A translation unit shall not
#defineor#undefnames lexically identical to keywords, to the identifiers listed in Table 3, or to the attribute-tokens described in 7.6.
Table 3 includes override and final. In your case, your macro should be fine too, because in C++03 override is not a keyword, so defining a macro does not violate the rule above, and a C++11 compiler will never see that macro definition. But I still prefer the method above.
回答3:
That solution seems like a pretty reasonable way to solve the problem you're faced with. It's perfectly fine to #define override in C++98 because it's not a keyword there.
来源:https://stackoverflow.com/questions/22259199/elegant-way-to-deal-with-override-in-c98-c11-cross-compilable-code