草庐IT

C++:覆盖已弃用的虚拟方法时的弃用警告

coder 2024-02-22 原文

我有一个纯虚类,它有一个应该是 const 的纯虚方法,但不幸的是不是。该接口(interface)在一个库中,该类由单独项目中的几个其他类继承。

我试图在不破坏兼容性的情况下(至少在一段时间内)使此方法成为 const,但我找不到在非 const 方法重载时产生警告的方法。

以下是到目前为止我能够生成的示例:

  • 第 0 阶段:变革之前。只有 Interface::doSomething() 方法的非常量版本存在,并且它是纯虚拟的。
  • 第 1 阶段:过渡期间。 Interface::doSomething() 方法的 const 和非 const 版本都存在。它们都有一个默认实现,以允许旧样式和新样式实现(在这个阶段它们不能是纯虚拟的,因为每个继承类只会覆盖其中一个)。 const 版本调用非常量版本以确保与旧实现的兼容性,非常量版本断言,因为它永远不应该被调用。
  • 第 2 阶段:只有 Interface::doSomething() 方法的非 const 版本存在,并且它是纯虚拟的。

阶段 1 中,我希望能够在类重写 Interface::doSomething() 的非常量版本时发出警告,在为了警告用户他们应该更新他们的代码,所以当我切换到 Stage 2 时,破坏其他人代码的机会非常低。 不幸的是我找不到办法做到这一点。我尝试了几种标志组合,包括 GCC 和 Clang。我唯一能做的就是让编译失败(例如,将其更改为 final),但这不是我想要处理的方式。有没有办法产生警告?

#include <iostream>
#include <cassert>

class Interface
{
public:
    virtual ~Interface() = default;

// callDoSomething method:
// - stage 0: non const
// - stage 1-2: const
#if (STAGE == 0)
    void callDoSomething() { doSomething(); }
#else
    void callDoSomething() const { doSomething(); }
#endif

protected:

// non-const doSomething() method:
// - stage 0: pure virtual
// - stage 1: virtual with assert in default implementation (should never be called)
// - stage 2: removed
#if (STAGE == 0)
    virtual void doSomething() = 0;
#elif (STAGE == 1)
    [[deprecated("Overload const version instead")]]
    virtual void doSomething()
    {
        assert(false);
    }
#endif

// const doSomething() method
// - stage 0: N/A
// - stage 1: virtual with default implementation (calls the non-const overload)
// - stage 2: pure virtual
#if (STAGE == 1)
    virtual void doSomething() const
    {
        std::cout << __PRETTY_FUNCTION__ << '\n';
        std::cout << "  calling non const version\n";
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
        const_cast<Interface*>(this)->doSomething();
#pragma GCC diagnostic pop
    }
#elif (STAGE == 2)
    virtual void doSomething() const = 0;
#endif
};


// Old style implementation: non-const doSomething()
// Allowed only in stages 0 and 1
#if (STAGE == 0 || STAGE == 1)
class Implementation_old : public Interface
{
public:
    virtual ~Implementation_old() = default;

protected:
    virtual void doSomething() override
    {
        std::cout << __PRETTY_FUNCTION__ << '\n';
    }
};
# endif


// Old style implementation: const doSomething()
// Allowed only in stages 1 and 2
#if (STAGE == 1 || STAGE == 2)
class Implementation_new : public Interface
{
public:
    virtual ~Implementation_new() = default;

protected:
    virtual void doSomething() const override
    {
        std::cout << __PRETTY_FUNCTION__ << '\n';
    }
};
#endif


int main(int argc, char *argv[])
{
    Interface* iface = nullptr;

#if (STAGE == 0 || STAGE == 1)
    iface = new Implementation_old;
    iface->callDoSomething();
    delete iface;
#endif

#if (STAGE == 1)
    std::cout << "-------------------\n";
#endif

#if (STAGE == 1 || STAGE == 2)
    iface = new Implementation_new;
    iface->callDoSomething();
    delete iface;
#endif

    iface = nullptr;

    return 0;
}

这是使用 STAGE 的 3 个定义构建示例的 CMakeLists.txt 文件

cmake_minimum_required(VERSION 3.5)
project(test_deprecate_non_const)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

add_executable(main_stage_0 main.cpp)
target_compile_definitions(main_stage_0 PRIVATE STAGE=0)

add_executable(main_stage_1 main.cpp)
target_compile_definitions(main_stage_1 PRIVATE STAGE=1)

add_executable(main_stage_2 main.cpp)
target_compile_definitions(main_stage_2 PRIVATE STAGE=2)

最佳答案

在使用已弃用的接口(interface)时发出警告会很好。然而,我的尝试和你的一样都失败了。我认为不幸的是,属性在设计时并未考虑到这一点。我认为属性适用于实体的名称,这意味着只有在按名称调用方法时才会收到警告。但是我没有研究这方面的标准。

所以,怀着悲痛的心情,我来偷一个结论this answer到一个稍微相关的帖子:

Tell your users that the function is deprecated and shouldn't be used, then move on.

关于C++:覆盖已弃用的虚拟方法时的弃用警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49011990/

有关C++:覆盖已弃用的虚拟方法时的弃用警告的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  6. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  7. ruby-on-rails - 在混合/模块中覆盖模型的属性访问器 - 2

    我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah

  8. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  9. ruby - 在院子里用@param 标签警告 - 2

    我试图使用yard记录一些Ruby代码,尽管我所做的正是所描述的here或here#@param[Integer]thenumberoftrials(>=0)#@param[Float]successprobabilityineachtrialdefinitialize(n,p)#initialize...end虽然我仍然得到这个奇怪的错误@paramtaghasunknownparametername:the@paramtaghasunknownparametername:success然后生成的html看起来很奇怪。我称yard为:$yarddoc-mmarkdown我做错了什么?

  10. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

随机推荐