jjzjj

c++ - 用 CRTP 替换非纯虚函数

coder 2024-02-09 原文

我正在通过其 C++ SDK 为应用程序编写插件。该机制相当简单。插件通过预定义的接口(interface)提供其功能。这是通过让服务器类从每个接口(interface)的一个实现类继承来完成的,该实现类包含纯虚函数或具有默认实现的非纯函数。
这非常实用,因为 SDK 客户端只需覆盖插件所需的那些方法和/或为(罕见的)没有默认值的方法提供实现。

一直困扰我的是,一切都在编译时已知。与运行时多态相关的虚函数表和机制在这里只是为了提供默认实现。
我试图在保持便利的同时消除这种开销。

作为一个(非常人为的)示例,假设我有几个服务器提供一个接口(interface)(名为 Blah),该接口(interface)仅包含一个没有默认实现的方法。

// SDK header
struct OldImpl_Blah {
    virtual ~OldImpl_Blah() =default;
    virtual int mult(int) =0;
};

// plugin source
class OldServer3 : public OldImpl_Blah {
public:
    int mult(int i) override { return 3 * i; }
};

class OldServer5 : public OldImpl_Blah {
public:
    int mult(int i) override { return 5 * i; }
};

对于纯虚函数,直接 CRTP 工作得很好。

// SDK header
template <typename T>
struct NewImpl_Blah {
    int mult(int i) { return static_cast<T*>(this)->mult(i); }
};

// plugin source
class NewServer3 : public NewImpl_Blah<NewServer3> {
public:
    int mult(int i) { return 3 * i; }
};

class NewServer5 : public NewImpl_Blah<NewServer5> {
public:
    int mult(int i) { return 5 * i; }
};

问题在于纯虚函数,即当方法有默认实现时。

// SDK header
struct OldImpl_Blah {
    virtual ~OldImpl_Blah() =default;
    virtual int mult(int i) { return i; }    // default
};

// plugin source
class OldServer3 : public OldImpl_Blah {
public:
    int mult(int i) override { return 3 * i; }
};

class OldServer5 : public OldImpl_Blah {
public:
    int mult(int i) override { return 5 * i; }
};

我试图将 CRTP 与一些表达 SFINAE 技巧结合起来,但失败了。
我想我需要的是某种代码调度,其中基类要么提供默认实现,要么将其参数转发给派生类中的实现(如果存在)。
问题似乎是分派(dispatch)应该依赖于基类中编译器尚不可用的信息。

一个简单的解决方案是删除代码中的 virtualoverride 关键字。但是编译器不会检查函数签名是否匹配。
这种情况有一些众所周知的模式吗?我问的是可能的吗?

(请使用小字,因为我对模板的专业知识有点浅。谢谢。)

最佳答案

与往常一样,另一个间接级别是解决方案。在这种特殊情况下,这是众所周知的公共(public)非虚函数调用私有(private)或 protected 虚函数的技术。它有自己的用途,与这里讨论的内容无关,所以无论如何都要检查一下。通常它是这样工作的:

struct OldImpl_Blah {
piblic:
    virtual ~OldImpl_Blah() = default;
    int mult(int i) { return mult_impl(i); }
protected:
    virtual int mult_impl(int i) { return i; }
};

// plugin source
class OldServer3 : public OldImpl_Blah {
protected:
    int mult_impl(int i) override { return 3 * i; }
};

对于 CRTP,它完全一样:

template <class T>
struct OldImpl_Blah {
piblic:
    virtual ~OldImpl_Blah() = default;
    int mult(int i) { return static_cast<T*>(this)->mult_impl(i); }
protected:
    virtual int mult_impl(int i) { return i; }
};

// plugin source
class OldServer3 : public OldImpl_Blah<OldServer3> {
protected:
    int mult_impl(int i) override { return 3 * i; }
};

免责声明:CRTP 据说通过要求函数是虚拟 来消除虚拟调用开销。我不知道当函数保持 virtual 时 CRTP 是否有任何性能优势。

关于c++ - 用 CRTP 替换非纯虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36270985/

有关c++ - 用 CRTP 替换非纯虚函数的更多相关文章

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

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

  2. ruby 正则表达式 - 如何替换字符串中匹配项的第 n 个实例 - 2

    在我的应用程序中,我需要能够找到所有数字子字符串,然后扫描每个子字符串,找到第一个匹配范围(例如5到15之间)的子字符串,并将该实例替换为另一个字符串“X”。我的测试字符串s="1foo100bar10gee1"我的初始模式是1个或多个数字的任何字符串,例如,re=Regexp.new(/\d+/)matches=s.scan(re)给出["1","100","10","1"]如果我想用“X”替换第N个匹配项,并且只替换第N个匹配项,我该怎么做?例如,如果我想替换第三个匹配项“10”(匹配项[2]),我不能只说s[matches[2]]="X"因为它做了两次替换“1fooX0barXg

  3. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  4. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  5. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  6. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  7. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  8. C51单片机——实现用独立按键控制LED亮灭(调用函数篇) - 2

    说在前面这部分我本来是合为一篇来写的,因为目的是一样的,都是通过独立按键来控制LED闪灭本质上是起到开关的作用,即调用函数和中断函数。但是写一篇太累了,我还是决定分为两篇写,这篇是调用函数篇。在本篇中你主要看到这些东西!!!1.调用函数的方法(主要讲语法和格式)2.独立按键如何控制LED亮灭3.程序中的一些细节(软件消抖等)1.调用函数的方法思路还是比较清晰地,就是通过按下按键来控制LED闪灭,即每按下一次,LED取反一次。重要的是,把按键与LED联系在一起。我打算用K1来作为开关,看了一下开发板原理图,K1连接的是单片机的P31口,当按下K1时,P31是与GND相连的,也就是说,当我按下去时

  9. ruby - Ruby gsub 替换中的行为不一致? - 2

    两个gsub产生不同的结果。谁能解释一下为什么?代码也可在https://gist.github.com/franklsf95/6c0f8938f28706b5644d获得.ver=9999str="\tCFBundleDevelopmentRegion\n\ten\n\tCFBundleVersion\n\t0.1.190\n\tAppID\n\t000000000000000"putsstr.gsub/(CFBundleVersion\n\t.*\.).*()/,"#{$1}#{ver}#{$2}"puts'--------'putsstr.gsub/(CFBundleVersio

  10. ruby-on-rails - 将字符串转换为 ruby​​-on-rails 中的函数 - 2

    我需要一个通过输入字符串进行计算的方法,像这样function="(a/b)*100"a=25b=50function.something>>50有什么方法吗? 最佳答案 您可以使用instance_eval:function="(a/b)*100"a=25.0b=50instance_evalfunction#=>50.0请注意,使用eval本质上是不安全的,尤其是当您使用外部输入时,因为它可能包含注入(inject)的恶意代码。另请注意,a设置为25.0而不是25,因为如果它是整数a/b将导致0(整数)。

随机推荐