本文介绍了优雅的方式来处理重写在C ++ 98,C ++ 11交叉可编译的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码,它有可选的内置代码,试图检测C ++ 0X。让我们假装这是有效的(讨论多么坏,如何跨平台,这是超出了这个问题的范围)。假设它有一个#define DETECTCXX0X 。如果它是C ++ 0X。

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

您有其他选择吗?

(我认为正确的做法是不要使用显式覆写)。

(I suppose the correct thing to do is to just not use explicit overriding).

推荐答案

正如Igor Tandetnik指出它在C ++ 11和C ++ 98中是合法的:

As Igor Tandetnik points out it's legal in C++11 and C++98 to say:

int override = 10;

因为 override 在C ++ 11。如果你的代码这样做,那么你的宏将在C ++ 98模式下。如果你禁止使用这样的标识符,然后你的方法将正常工作。唯一的问题是,你可能会忘记该规则,很难理解错误消息。

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.

另一种选择是Praetorian的解决方案:

Another option is Praetorian's solution:

#ifndef DETECTCXX0X
#define OVERRIDE
#else
#define OVERRIDE override
#endif

但是,这使得难以阅读代码,IMO。

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

不能避免非C ++ 11编译器,然后第二个最好的选择,如果你有linter,是使用它 #define override 。第三最好是不使用这个特定的C ++ 11功能。在我看来,最不可取的选项是 #define OVERRIDE override

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.

这篇关于优雅的方式来处理重写在C ++ 98,C ++ 11交叉可编译的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 11:13