强制使用c ++覆盖关键字? [英] make usage of the c++ override keyword mandatory?

查看:71
本文介绍了强制使用c ++覆盖关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很喜欢c ++ 11的新override关键字,我正尝试将它添加到我的代码中的任何地方.如果编译器可以帮助我发现所有这些情况,那就太好了.

I really like the new override keyword of c++11 and i am trying to add it to my code everywhere. It would be nice if the compiler would help me spot all of these cases.

是否有任何方法可以使编译器的行为像override关键字是强制性的?我正在使用Visual Studio 2012

Is there any way to make the compiler behave as if the override keyword is mandatory? I am using visual studio 2012

例如,我希望编译器发出错误/警告:

For example, I want the compiler to emit an error/warning:

class Base{
public:
    virtual void the_virtual(){}
};
class derive:public Base{
public:
    void the_virtual(){} //warning/error wanted here
};

推荐答案

我将从基础知识入手,为该类提供 virtual 析构函数:编译器会对此发出警告.

I would start with the basics and give the class a virtual destructor: compilers tend to warn about that.

关于实际问题,极不可能强制使用 override ,因为存在太多需要修补的代码.标准委员会对此类问题的普遍看法是,这是实施质量问题:编译器完全可以自由警告所有可能存在问题的声明.也就是说,您会游说编译器供应商或静态分析器供应商针对这种情况创建警告....,如果您不认为可以让供应商应用支票,请自己创建支票!使用例如

With respect to the actual question, it is highly unlikely that the use of override will be made mandatory as there is way too much code in existence which would need to get patched up. The general view taken by the standards committee on issues like these is that it is a quality of implementation issue: compilers are entirely free to warn about all sorts of potentially problematic declaration. That is, you'd lobby your compiler vendor or your static analyzer vendor to create a warning for this situation. ... and if you don't think you can make the vendors apply the check, create it yourself! Checking whether there is an override keyword when overriding a virtual function using, e.g., clang is fairly simple.

另外,下面是一个示例,其中强制使用 override 起作用:

Also, here is an example where a mandatory use of override would not work:

struct Base1 {
    virtual ~Base1() {}
    virtual int f() { return 0; }
};
struct Base2 {
    int f() { return 1; }
};

template <typename Base>
struct Derived: Base { 
    int f() { return 2; }
};

int main()
{
    Derived<Base1> d1;
    Derived<Base2> d2;
}

在类模板 Derived 中,函数 f()可能是也可能不是重写.您不能有条件地在其中放置 override .

In the class template Derived the function f() may or may not be an override. You can't conditionally put override there.

这篇关于强制使用c ++覆盖关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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