I have code like this
if (...) {
const auto & h = std::make_shared<ClassB>();
... // here may be the function that uniquely belongs to ClassB
...
}
else (...) {
const auto & h = std::make_shared<ClassC>();
... // here may be the function that uniquely belongs to ClassC
...
}
h->someFunction();
The last line of the above code is invalid because I use a variable that is declared inside the if-else clause. To use h I have to declare it before the if-else clause. But I can't because I don't know what type h belongs to before entering it.
I know I can declare it using ternary operator. But I don't want to because I think it will be redundant to have both ternary operator and if-else clause. Sorry, I can't. The compiler will complain "error: conditional expression is ambiguous;".
Are there any ways to keep only one if-else clause (no ternary operator) and I still can refer to h outside that if-else clause?
Aucun commentaire:
Enregistrer un commentaire