简体   繁体   中英

Overload Base class virtual function from template Derived class

I want several datas accessible from a pointer table. Datas can be of any type (eg: int, double, string). I have created a Base class to use pointers from and I want to derive a template class which will do the typing.

I got the following message and I don't know what is wrong (even if I have a strong feeling that I misunderstand a lot...):

error: 'virtual double Base::get_value()' cannot be overloaded with 'virtual int Base::get_value()'

class Base
{
    public :        
        virtual int get_value() = 0;
        virtual double get_value() = 0;
};

template <typename T>
class Derived : public Base
{
    private :
        T m_value;
        
    public :
        Derived(T val):Base(), m_value(val) {}
    
        virtual T get_value() { return m_value; }
};

You cannot overload a function based on the return type alone. Hence this cannot work:

class Base
{
    public :        
        virtual int get_value() = 0;
        virtual double get_value() = 0;
};

If you call b->get_value() there is no way to disambiguate the two.

Next in Derived you probably want to override the method from the base, for this use the keyword override to make your intent clear and get better compiler errors::

virtual T get_value() override { return m_value; }

However, due to the issue in Base this won't work either. You need to rethink your design. A derived class must implement all abstract methods of Base to be a non-abstract class. You cannot pick which one to implement.

It looks like you are trying to reimplement something similar to std::any or std::variant . Neither of the two is trivial to implement from scratch. If you care about your own implementation then I suggest you to look at how they are implemented. If not, just use them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM