You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++继承体系下如何优化设计使子类无需重复实现GetType系列函数

优化方案:使用*CRTP(奇异递归模板模式)*实现逻辑复用

核心思路是新增一个模板化的中间派生层,统一实现虚函数GetType的通用逻辑,后续新增子类仅需要定义自身的静态GetType_S方法即可,不需要重复实现虚函数,完全无宏依赖,编译期完成逻辑生成,无额外运行时开销。

完整优化代码

#include <iostream>

// 基类保留统一的多态接口定义
class Base 
{
public:
    static int GetType_S()
    {
        return 1;
    }
    virtual int GetType()
    {
        return GetType_S();
    }
    virtual ~Base() = default; // 基类新增虚析构,避免多态场景下内存泄漏
};

// CRTP中间层,统一封装虚函数实现逻辑
template <typename Derived>
class BaseImpl : public Base
{
public:
    int GetType() override
    {
        return Derived::GetType_S();
    }
};

// 子类仅需要继承对应模板实例、实现自身的静态方法即可
class Son1 : public BaseImpl<Son1>
{
public:
    static int GetType_S()
    {
        return 2;
    }
};

class Son2 : public BaseImpl<Son2>
{
public:
    static int GetType_S()
    {
        return 3;
    }
};

功能验证用例

原有多态特性、静态方法调用能力完全保留:

int main()
{
    Base base;
    Base* p1 = new Son1();
    Base* p2 = new Son2();
    
    std::cout << base.GetType() << std::endl; // 输出1
    std::cout << p1->GetType() << std::endl; // 输出2
    std::cout << p2->GetType() << std::endl; // 输出3
    std::cout << Son1::GetType_S() << std::endl; // 静态调用正常输出2
    
    delete p1;
    delete p2;
    return 0;
}

内容的提问来源于stack exchange,提问作者yunate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 23:57:04