Accessing a method from a templated derived class

2019-04-17 09:57发布

How do I get around this? I clearly cannot make the value() method virtual as I won't know what type it is beforehand, and may not know this when accessing the method from b:

class Base
{
public:
    Base() { }
    virtual ~Base() { }
private:
    int m_anotherVariable;
};

template <typename T>
class Derived : public Base
{
public:
    Derived(T value) : m_value(value) { }
    ~Derived() { }

    T value() { return m_value; }
    void setValue(T value) { m_value = value; }
private:
    T m_value;
};

int main()
{
    Base* b = new Derived<int>(5);

    int v = b->value();

    return 0;
}

Compilation errors:

error: 'class Base' has no member named 'value'

8条回答
我命由我不由天
2楼-- · 2019-04-17 10:40

Why don't make Base template-based class too? Then you can have value as a virtual member.

Or you can downcast b to Derived.

查看更多
Melony?
3楼-- · 2019-04-17 10:46

It looks like you want dynamic polymorphism but using only the "static polymorphism" of templates.

If you want dynamic polymorphism you do need virtual members in your base class ( along with your virtual destructor ) or the down_cast if you do not have a common interface.

If not, remove the virtual destructor and use only pointers to or instances of derived types.

About Base as a template :

It will prevent you from having a single base class for dynamic polymorphism as Base< int > and Base< other > will be incompatibles.

查看更多
登录 后发表回答