函数属性是否继承? [英] Are function attributes inherited?

查看:49
本文介绍了函数属性是否继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个带有 属性的虚函数

[[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 和类 中声明了虚成员函数 vf>派生,直接或间接派生自Base,成员函数vf同名,parameter-type-list (11.3.5)、cv-qualificationref-qualifier(或没有相同)作为 Base::vf 被声明,然后 Derived::vf 也是虚拟的(无论它是否如此声明)并且它覆盖 Base::vf.[..]

[class.virtual]/2: If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list (11.3.5), cv-qualification, and ref-qualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆