函数属性是否被继承? [英] Are function attributes inherited?
问题描述
如果我有一个带有属性
[[nodiscard]]
virtual bool some_function() = 0;
该属性是否隐式应用于该函数的替代?
Does that attribute get implicitly applied to overrides of that function?
bool some_function() override;
还是我需要再次使用该属性?
Or do I need the attribute again?
[[nodiscard]]
bool some_function() override;
推荐答案
在C ++ 17的措辞中,我看不到任何证据表明属性是由重写函数继承的.
I can't see any evidence in the C++17 wording that attributes are inherited by overriding functions.
我能找到的最相关的部分是覆盖规则:
The most relevant section I can find is the rules for overriding:
[class.virtual]/2:
如果在类Base
和类Derived
中声明了虚拟成员函数vf
,这些成员函数直接或间接从Base
派生,则成员函数vf
具有相同名称,参数类型列表(11.3.5), cv限定和 ref-qualifier (或不存在)与Base::vf
相同),那么Derived::vf
也是虚拟的(无论是否声明),并且覆盖Base::vf
. [..]
[class.virtual]/2:
If a virtual member functionvf
is declared in a classBase
and in a classDerived
, derived directly or indirectly fromBase
, a member functionvf
with the same name, parameter-type-list (11.3.5), cv-qualification, and ref-qualifier (or absence of same) asBase::vf
is declared, thenDerived::vf
is also virtual (whether or not it is so declared) and it overridesBase::vf
. [..]
尽管这段话从一个稍微不同的角度解决了这个问题,但我认为足以证明仅继承了虚拟性(并且在确定一个功能是否覆盖另一个功能时,属性根本不起作用).话虽这么说,但我认为这没有被充分说明,至少可以做一个澄清的说明.
While this passage attacks the problem from a slightly different angle, I think it's enough to show that only virtualness is "inherited" (and that attributes don't come into play at all when deciding whether one function overrides another). That being said, I think this is slightly underspecified and could do with a clarifying note at the very least.
当然,这很快变得复杂起来.给出以下示例:
Of course, this quickly gets complicated. Given the below example:
struct B {
[[nodiscard]] virtual bool foo() { return true; }
};
struct D : B {
bool foo() override { return false; }
};
int main() {
D().foo();
}
Clang不会发出警告.但是,可以通过基本指针访问该函数.
Clang will not issue a warning. However, access the function through a base pointer and it will.
struct B {
[[nodiscard]] virtual bool foo() { return true; }
};
struct D : B {
bool foo() override { return false; }
};
int main() {
D d;
((B*)&d)->foo();
}
我不确定这是什么意思.
What that means for your question, I'm not sure.
再次,我想从标准中获得更多有关此主题的指导.
Again, I'd like to see a bit more guidance from the standard on this topic.
这篇关于函数属性是否被继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!