Assuming the following couple of classes Base
and Derived
, is there a way to either a) declare a virtual method value() on the base class without a specific return type (which I doubt it's possible) or 2) have different templated types on the same vector/container (which is why I am using pointers to a non-template abstract base class)? I am using C++11 which doesn't allow me to use auto
without a return type.
#include <vector>
#include <iostream>
class Base {
public:
Base() { /* */ }
// virtual auto value() const = 0; // <- need return type!!
};
template <typename T>
class Derived : public Base{
public:
explicit Derived(const T& _val) : member(_val) { /* */ }
T value() const { return member; }
protected:
T member;
};
void doStuff(const std::vector<Base*>& _data) {
// ...
for (auto& obj : _data) {
std::cout << obj->value() << std::endl; // error - ‘class Base’ has no member named ‘value’
}
}
int main(int argc, char const *argv[]) {
std::vector<Base*> data;
Derived<float> foo(0.5);
Derived<int> bar(47);
data.push_back(&foo);
data.push_back(&bar);
doStuff(data);
return 0;
}
Aucun commentaire:
Enregistrer un commentaire