mbadawi23 mbadawi23 - 3 months ago 10
C++ Question

C++: How to define a virtual function with generic return type?

I'm trying to define a base a class in C++ that has pure virtual methods to be implemented by children classes.

I would like to define setter and getter functions for basic types in the base class, but I would like the derived class to be able to determine the basic type of the getter and setter. For instance my base class would look like this:

class Value
{
public:
Value();
template <class T>;
virtual T getValue() = 0;
virtual void setValue(T val) = 0;
}


and my child class would look something like this:

class IntValue : public Value
{
public:
IntValue();
template <class T>
T getValue() {return _val};
void setValue(T val) {_val = val};
private:
int _val;
}


Of course the above code does not work. Any ideas on how to achieve this? Thanks in advance.

J_D J_D
Answer

If I understood your problem correctly, rewriting your code to

template <class T>
class Value
{
public:
    Value();
    virtual T getValue() = 0;
    virtual void setValue(T val) = 0;
};


class IntValue : public Value<int>
{
public:
    IntValue();

    int getValue() {return _val;}
    void setValue(int val) {_val = val;}
private:
    int _val;
};

should work