jeudi 5 août 2021

C++ workaround for templated polymorphism

class Base{
public:
    template <typename T> T getValueAs()
    {
        //should return (T)this->getValue()
    }
    template <typename T> void setValueFrom(T val)
    {
        //should call this->setValue((Impl::value_type)val)
    }   
}

template<typename T> class Impl : public Base {
public:
    virtual void setValue(const T& val){ ... }
    virtual T getValue() const{ ... }
protected:
    T value;
}

//also some very speficic impl would be
class NumVal : public Base<int>{
}

I want to use it as :

Impl<float> var;
var.setValue(42.0f);
Base* baseVar = (Base*)&var;

int convertedVal = baseVar->getValueAs<int>(); // should return (int)(42.0f)

I know we can't override the template member function, the restriction here is Base class does not know the exact value type of Impl class, is there an alternative to achieve something like that?

otherwise, I need to implement very specific conversion on base class to be overridden on descendant class like :

class Base{
public:
   virtual std::string getString() = 0;
   virtual int getInt() = 0;
   virtual bool getBool() = 0;
}

so what i need is just Base::get<T>()





Aucun commentaire:

Enregistrer un commentaire