You need to enable JavaScript to run this app. 如何用模板将运行时多态类改写为C++11兼容的编译时多态单类
优惠活动
大模型
产品
解决方案
定价
更多

如何用模板将运行时多态类改写为C++11兼容的编译时多态单类

实现方案(C++11兼容,无运行时多态开销)

两种方案均可实现编译期确定灯光类型,完全消除虚表查找的运行时开销,你可以根据业务复杂度选择:

方案1:模板+特性类(Traits)实现,扩展性更优

适合后续可能新增更多灯光类型的场景,代码结构清晰,无冗余逻辑:

#include <string>
#include <array>
#include <memory>

class Color
{
public:
    Color(std::string color_name) : color_name_(color_name) { }
private:
    std::string color_name_;
};

// 灯光类型标签
struct NormalLightTag {};
struct SpecialLightTag {};

// 灯光特性类,不同特化存储对应类型的常量
template <typename Tag>
struct LightTraits;

template <>
struct LightTraits<NormalLightTag> {
    static constexpr int resolution = 9;
    static std::array<Color, 3> GetColors() {
        return {Color("blue"), Color("red"), Color("purple")};
    }
};

template <>
struct LightTraits<SpecialLightTag> {
    static constexpr int resolution = 13;
    static std::array<Color, 3> GetColors() {
        return {Color("yellow"), Color("magenta"), Color("orange")};
    }
};

// 通用灯光类,所有公共逻辑均在此实现
template <typename Tag>
class Light {
public:
    static std::unique_ptr<Light<Tag>>& GetInstance() {
        static std::unique_ptr<Light<Tag>> instance(new Light<Tag>());
        return instance;
    }

    // 示例公共方法,原有LightBase的所有方法都可以移到这里
    void DoSomething() {
        int res = LightTraits<Tag>::resolution;
        std::array<Color, 3> colors = LightTraits<Tag>::GetColors();
        // 原有业务逻辑
    }

private:
    Light() = default;
};

// 编译期选择对应灯光类型
#if defined(CONFIG_LIGHT_TYPE_NORMAL)
using SelectedLight = Light<NormalLightTag>;
#elif defined(CONFIG_LIGHT_TYPE_SPECIAL)
using SelectedLight = Light<SpecialLightTag>;
#endif

使用时直接调用SelectedLight::GetInstance()即可拿到单例,所有方法调用无任何运行时开销。

方案2:预处理器直接注入常量,实现最简

如果只有两种灯光类型,不需要预留扩展能力,直接用宏判断注入常量即可,代码最少:

#include <string>
#include <array>
#include <memory>

class Color
{
public:
    Color(std::string color_name) : color_name_(color_name) { }
private:
    std::string color_name_;
};

class Light {
public:
    static std::unique_ptr<Light>& GetInstance() {
        static std::unique_ptr<Light> instance(new Light());
        return instance;
    }

    // 所有公共方法均在此实现
    void DoSomething() {
        int res = resolution;
        auto& colors = colors_;
        // 原有业务逻辑
    }

private:
    Light() = default;

#if defined(CONFIG_LIGHT_TYPE_NORMAL)
    static constexpr int resolution = 9;
    std::array<Color, 3> colors_ = {Color("blue"), Color("red"), Color("purple")};
#elif defined(CONFIG_LIGHT_TYPE_SPECIAL)
    static constexpr int resolution = 13;
    std::array<Color, 3> colors_ = {Color("yellow"), Color("magenta"), Color("orange")};
#endif
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 06:30:04