我不知道C++11引入了属性。现在我发现了,我想知道为什么override
和final
被添加为具有特殊含义的标识符而不是标准属性。
override
的目的是生成编译时错误,这也是许多标准属性的目的。它们似乎适合这个概念,但我可能错过了其中的原因。
在对C++11的FCD进行评论US 44的回应之前,它们曾经存在。
Even if attributes continue to be standardized over continued objections from both of the two vendors who are cited as the principal prior art, we can live with them with the exception of the virtual override controls. This result is just awful, as already shown in the example in 7.6.5 (excerpted):
class D [[base_check]] : public B { void some_func [[override]] (); virtual void h [[hiding]] (char*); };
Here we have six keywords (not counting
void
andchar
): three normal keywords, and three[[decorated]]
keywords. There has already been public ridicule of C++0x about this ugliness. This is just a poor language design, even in the face of backward compatibility concerns (e.g., that some existing code may already use those words as identifiers) because those concerns have already been resolved in other ways in existing practice (see below). More importantly, this is exactly the abuse of attributes as disguised keywords that was objected to and was explicitly promised not to happen in order to get this proposal passed. The use of attributes for the virtual control keywords is the most egregious abuse of the attribute syntax, and at least that use of attributes must be fixed by replacing them with non-attribute syntax. These virtual override controls are language features, not annotations.It is possible to have nice names and no conflicts with existing code by using contextual keywords, such as recognizing the word as having the special meaning when it appears in a grammar position where no user identifier can appear, as demonstrated in C++/CLI which has five years of actual field experience with a large number of customers (and exactly no name conflict or programmer confusion problems reported in the field during the five years this has been available):
class D : public B { void some_func() override; // same meaning as [[override]] - explicit override virtual void h (char*) new; // same meaning as [[hiding]] - a new function, not an override }; int override = 42; // ok, override is not a reserved keyword
The above forms are implementable, have been implemented, have years of practical field experience, and work. Developers love them. Whether the answer is to follow this existing practice or something else, there needs to be a more natural replacement for the currently
[[attributed]]
keywords for virtual override control which is an ugly novelty that has no field experience and that developers have already ridiculed.
简单引用http://en.cppreference.com/w/cpp/language/attributes:
属性提供了实现定义的语言扩展的统一标准语法,例如GNU和IBM语言扩展attribute((...)),Microsoft扩展__declspec()等。
这使得标准语言关键字不是属性变得非常清晰。
[[noreturn]]
一样被实现为属性。 - François Andrieux
noexcept
不是一个?宇宙之谜。 - Hatted Rooster