I would like to achieve something like following on c++14, basically derived class can have different type of return type (e.g int, double, string, etc)
class Base {
public:
virtual auto value() = 0; // I know this won't compile
};
class Derived1 : public Base {
public:
double value() override {
return 1.0;
};
};
class Derived2 : public Base {
public:
int value() override {
return 1;
};
};
I know above code won't compile but I'm trying to achieve something like that using any possible way or pattern (I've tried template, CRTP, visitor but nothing can satisfy my following code)
Derived1 d1;
Derived2 d2;
std::vector<Base*> base = {&d1, &d2);
for (const auto* b : base) {
std::cout << b->value();
}
The best I can get with template is something like
Derived1 d1;
Derived2 d2;
std::vector<Base*> base = {&d1, &d2);
for (const auto* b : base) {
if (dynamic_cast<Derived1>(b)) {
std::cout << b->value<double>();
} else if (dynamic_cast<Derived2>(b)) {
std::cout << b->value<int>();
}
}
but if I have 100 types of Derived class, it won't look that pretty :D