使用模板将多态类重写为一个类编译时多态

问题描述

在我当前的代码中,我使用运行时多态从 LightBase 类创建不同的“光”子类型。然而,光类型在编译时就已经知道了(预处理器会选择正确的变体)。所以我认为它真的不是正确的工具,因为它很慢(虚拟 getter 函数的 vtable 查找)并且可以在编译时完成。我只是不知道如何......可以用模板来完成吗?我在模板编程方面没有太多经验,所以我不知道什么是可能的。

本质上,我想实例化一个 normalLight 或 SpecialLight 类型的子类,它们具有与 LightBase 相同的功能,但对一组不同的常量进行操作:

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

class LightBase {
    public:
        std::unique_ptr& GetInstance() { return instance_; }

    protected:
        const resolution;
        std::array<Color,0> = {  };
    // ..

    private:
        static std::unique_ptr<LightBase> instance_;
}

class normalLight : public LightBase
{
    protected:
        const resolution = 9;
        std::array<Color,3> { Color("blue"),Color("red"),Color("purple") };
    // ..
}

class SpecialLight : public LightBase
{
    protected:
        const resolution = 13;
        std::array<Color,3> { Color("yellow"),Color("magenta"),Color("orange") };
    // ..
}

#if defined CONfig_LIGHT_TYPE_norMAL
std::unique_ptr<LightBase> LightBase::instance_ = std::unique_ptr<normalLight>(new normalLight());
#elif defined CONfig_LIGHT_TYPE_SPECIAL
std::unique_ptr<LightBase> LightBase::instance_ = std::unique_ptr<SpecialLight>(new SpecialLight());
#endif

一个函数中,我可以有条件地检查模板参数(我猜),但它是一个类定义。此外,这件事应该在 C++11 中编译。有什么想法吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)