Reputation: 1722
auto
is comfortable to use but sometimes, for a matter of legibility while programming I would prefer to have the inferred type written in the source code instead of auto.
Is there a functionality of gcc/clang or some other tool/VSCode extension ( for linux or macos ) that takes as input the source files and spits back the same source files but with auto
replaced by its inferred type?
I tried googling but and the closest thing I've found is this StackOverflow question and it doesn't answer my question.
Upvotes: 4
Views: 643
Reputation: 28470
In general this is not always possible. In the following case, the compiler cannot substitute auto
with one type, because 3 different functions get actually instantiated.
template<typename T>
auto f(T x) {
auto y = x;
return y;
}
int main() {
f(1);
f('c');
f("c");
}
Someone in the comments says that it should substitute auto
for T
, because that's actually what happens in my trivial example: auto
is deduced to be the same type as T
is deduced to be, which in my opinion just means that in this example auto
is playing the same role as T
, which is the "placeholder" (maybe this is not the right terminology) for the type the compiler will deduce at each call site. Even if you substitute auto
for T
(in this trivial example), what invermation are you getting more than you had? Nothing.
If the main
above was instead
int main() {
f(1);
}
then yes, you or the compiler could substitute auto
with int
(or whatever), but in the original code, there would be no single substitution that would make happy all three lines inside that main
. The compile could just substitute the whole template function with a sequence of the various instantiations that it needs. And the number of those depends on how many different types are passed to f
in the whole codebase that makes use of f
.
If you write a library, with a nice template function in it, you cannot know which types it will be instatiated with, when I will use it in my code; so what are you substituting T
or auto
with?
Upvotes: 1