samedi 31 juillet 2021

Using templates to rewrite polymorphic class to one single class (compile time polymorphism)

In my current code I use runtime polymorphism to create different subtypes of "light" from a LightBase class. The lighttypes however are already known at compile time (preprocessor picks the right variant). So I figured it is really not the right tool to do so as it is slow (vtable lookup for virtual getter functions) and could be already done at compile time. I just don't know how... could it be done with templates? I don't have too much experience in template programming so I don't know what is possible.

Essentially I want to instantiate a subclass of either type NormalLight or SpecialLight which have the same functions as LightBase but operate on a different set of constants:

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

In a function I could conditionally check for a template parameter (I guess) but it's a class definition. Also, the thing should compile in C++11. Any ideas?

Aucun commentaire:

Enregistrer un commentaire