Is there a feature of the compiler for substituting auto with the inferred type in C++?


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.


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() {

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() {

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?

Answered By – Enlico

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published