C++ auto of varying template class instantiation
by Jerry Mcguire from LinuxQuestions.org on (#5A65Z)
Bad code but works:
Code:if (flag) {
auto p = std::make_unique<T<int>>();
p->foo();
p->bar();
}
else {
auto p = std::make_unique<T<double>>();
p->foo();
p->bar();
}How would you re-write the code?
Code:{
auto p; // error: declaration of 'auto p' has no initializer
if (flag) {
p = std::make_unique<T<int>>();
} else {
p = std::make_unique<T<double>>();
}
p->foo();
p->bar();
}


Code:if (flag) {
auto p = std::make_unique<T<int>>();
p->foo();
p->bar();
}
else {
auto p = std::make_unique<T<double>>();
p->foo();
p->bar();
}How would you re-write the code?
Code:{
auto p; // error: declaration of 'auto p' has no initializer
if (flag) {
p = std::make_unique<T<int>>();
} else {
p = std::make_unique<T<double>>();
}
p->foo();
p->bar();
}