c++ - C++ 静态多态性和方法名称

标签 c++ static-polymorphism

当我使用静态多态性(CRTP)时,有没有一种好的方法来给多态方法命名?

template <class Derived> 
struct Base
{
    void interface()
    {
        // ...
        static_cast<Derived*>(this)->implementation();
        // ...
    }

    static void static_func()
    {
        // ...
        Derived::static_sub_func();
        // ...
    }
};

struct Derived : Base<Derived>
{
    void implementation();
    static void static_sub_func();
};

因为,据我所知,接口(interface)和实现不能具有相同的名称(就像它们是虚拟的一样)。如果类层次结构很深,那就有点尴尬了。

也许有一些好的方法来处理它?或者也许我错了?

最佳答案

我的方法是避免继承(无论 CRTP 感觉多么可爱),而是使用聚合。类模板提供接口(interface),并依次提供具有实现的委托(delegate)类。它看起来像这样:

template <class Delegate>
struct Interface
{
    void do_something()
    {
        // ...
        delegate.do_something();
        // ...
    }

    Delegate delegate;
};

这有一个缺点,即向委托(delegate)对象提供构造函数参数比较尴尬,但管理起来并不太困难。

关于c++ - C++ 静态多态性和方法名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13645593/

相关文章:

c++ - CRTP静态多态: is it possible to replace the base class with a mock?

c++ - 是否有一种通用方法可以将函数模板改编为多态函数对象?

c++ - 静态多态性对实现接口(interface)有意义吗?

c++ - CRTP 与作为接口(interface)或 mixin 的虚拟函数

c++ - 为什么 utf-8 字符在 cmd.exe 中不显示?

c++ - 检测 windows jpeg 图标

c++ - 图数据结构的良好内存管理策略

c++ - 函数原型(prototype)和函数实现签名不一致地使用 const 可以吗?

c++ - Qt "Creating SSL context"错误在几台电脑上

c++ - CRTP - 我可以创建一个私有(private)方法吗?