Suppose I have a class such as Value defined below.
template <typename T>
class Value : public ValueInterface
{
public:
// ...
T getValue() const;
private:
T value_;
}
Can I refer to multiple Values of different types (that is, with different T types) in my code generically (to create a container, for example)? My first thought was if it’s possible to somehow declare a pure abstract class from which Value can inherit:
class ValueInterface
{
public:
?? getValue() const = 0;
}
template <typename T>
class Value : public ValueInterface
{
// ...
}
std::list<ValueInterface> lst;
Value<int> i(...);
Value<char> c(...);
lst.push_back(i);
lst.push_back(c);
int vi = i.getValue();
char vc = c.getValue();
If it is not possible, could you provide an alternate solution?
In C++ all expressions must have a type known to the compiler, but in your solution
lst.begin()->getValue()would not have any particular type.Although if you look carefully to your example you are not calling
ValueInterface::getValue()anywhere, just the subclasses versions.You can try the following:
Note that
getValue()is not (and cannot be) virtual.Now you can write the code from your example, but also:
If you use the wrong type in the
getValuecall then an exceptionstd::bad_castwill be thrown.