c++ - 函数属性是否继承?

标签 c++ attributes c++17

如果我有一个带有 attribute 的虚函数

[[nodiscard]] virtual bool some_function() = 0;

该属性是否隐式应用于该函数的覆盖?

bool some_function() override;

或者我是否需要再次使用该属性?

[[nodiscard]] bool some_function() override;

最佳答案

我给 C++ 委员会发了一封电子邮件,特别是 Core工作组,并提供了上述示例。

科里克莱默

It is currently unclear from the standard if attributes applied to virtual functions are inherited.

响应:

They are not. For them to be inherited, the Standard would have to explicitly say so, and it does not.

科里克莱默:

[After providing above code example] In the above example, I would expect both lines calling foo() to emit a compiler warning. I would hope that the attribute applies to all derived functions for consistency.

响应:

That's one perspective. Another is that, especially with covariant return types where the derived function returns a different type from that of the base function, it might very well be useful to make the base return type [[nodiscard]] but not the derived return type. There's currently no way to mark the derived function as not-[[nodiscard]].

More generally, it seems reasonable to get a different set of attributes when calling a derived function from those you get when calling the base function. If you know you have a derived class object, you have more specific information and behavior than if all you know is that it's a base class object, and attributes on member functions are part of that extra knowledge.

回复 Mike Miller C++ 核心工作组成员(2018 年 3 月 30 日)。

关于c++ - 函数属性是否继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49576298/

相关文章:

c++ - 初始化 constexpr - "illegal initialization of ' constexpr' 具有非常量表达式的实体”

c++ - QSound播放.wav文件时出现意外的null接收器

javascript - 要使用getAttribute(),还是不要使用getAttribute() : that is the question

c++ - 重写映射迭代器以返回dynamic_casted值

c++ - 在通用 lambda 中使用 constexpr-if 来确定参数的类型

c++ - C++17中数组索引范围的并行for循环

c++ - 在 C++ 中通过引用

c++ - DLL 中的控制台输出窗口

c# - 为什么我应该使用属性而不是实现接口(interface)?

session - 为什么 session 属性在 Servlet 中不是线程安全的?